【问题标题】:How can I call a Code Behind method with JavaScript?如何使用 JavaScript 调用 Code Behind 方法?
【发布时间】:2014-04-04 09:10:51
【问题描述】:

我想用 JS 调用 Code Behind 方法。我已经尝试过[WebMethod]。我推荐了this link。但是我背后的代码没有被调用。我在下面粘贴了代码,以便您找出实际问题。

Javascript

<script type="text/javascript">

function sendMail()
{
var arr = [];
arr.push('foo');
arr.push('bar');
arr.push('bazz');

 $.ajax({
                type: "POST",
                url: "~/Modules/Masters/Email.aspx/SendMail",
                data: "{info:arr}", // passing the parameter 
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (retValue) {
                    // Do something with the return value from.Net method
                }
            });
}
</script>

代码背后

[WebMethod]
public static string SendMail(string[] info)
{
    return "";
}

它是否需要任何库。我已经有了 &lt;script src="/js/jquery-1.9.1.js" type="text/javascript"&gt;&lt;/script&gt; 在我的 .Master 文件中。

【问题讨论】:

  • 您在 Firebug 中遇到错误吗?也许在“网络”标签中?
  • @markpsmith 没有错误。
  • 我假设当您说代码隐藏时,这是一个通用处理程序(.ashx?)而不是页面代码隐藏文件?当您尝试使用 AJAX 发布帖子时?
  • 不行,因为我点击的链接是aspx而不是ashx,我应该用ashx吗?
  • Issac 在他的回答中发现了您的主要问题。您不能在 javascript 中使用 ~,因为 ASP.NET 使用它来表示应用程序的根

标签: c# javascript jquery asp.net


【解决方案1】:

尝试从您的 ajax 调用中的 url 中删除“~”。我认为javascript不能很好地处理它。

【讨论】:

  • 你是对的...~ 被 ASP.NET 用作应用程序根目录的快捷方式,它不能与 javascript 一起使用
【解决方案2】:

有几件事可能是错误的,首先你的页面上也需要一个 ScriptManager!

【讨论】:

  • 是的,我有。我应该为此设置一些属性吗?
  • 我以前用过这种方法,略有不同但有相同的效果 -> techillumination.in/2013/07/… 也许看看它和你的解决方案有什么区别
【解决方案3】:

我正在使用 wcf 服务从纯 html 页面发送邮件可能对您有用,请查看此代码:

html页面:

   $(document).ready(function () {
        $('#reqinfo').click(function () {
           // debugger;
            var emailto = document.getElementById("emailid").value;
            if (emailto != "") {


                $.ajax({

                    type: "GET",
                    url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto,
                    // data: dat,
                    Accept: 'application/json',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                    //    debugger;


                    },
                    error: function (result) {
                       // debugger;

                    }
                });
            }
            else {
                //your validation message goes here
                return false;
            }
        });
    });

Wcf 服务:IEmailService 页面

  [OperationContract]
    [WebInvoke(UriTemplate = "/EmailService1/emaildata?Email={Email}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    string emaildata(string Email);

wcf 服务代码页:

public string emaildata(string Email)
    {
      //your email code.....
    }

Web.config 代码:

    <system.webServer>
   <defaultDocument>
   <files>
    <add value="Service1.svc" />

   </files>
   </defaultDocument>

  <handlers accessPolicy="Read, Execute, Script">
   <add name="ISAPI64" path="*" verb="*" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
</handlers>
 </system.webServer>

 <system.serviceModel>
  <services>
   <service name="SampleService" behaviorConfiguration="ServiceBehaviour">
     <endpoint address="" binding="webHttpBinding" contract="IService1" name="samendpoint" behaviorConfiguration="AjaxBehaviour">
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"   />

    </service>

    </services>

    <behaviors>

    <serviceBehaviors>
     <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true" httpHelpPageEnabled="true" />
    </behavior>
     </serviceBehaviors>
     <endpointBehaviors>
    <behavior name="AjaxBehaviour">
      <webHttp/>

    </behavior>
     </endpointBehaviors>

     </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
    <standardEndpoints>
       <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true"
      automaticFormatSelectionEnabled="true" />
      </webHttpEndpoint>
      </standardEndpoints>
     </system.serviceModel>

不要忘记在解决方案资源管理器中右键单击 wcf 服务并在 wcf 服务的标记中添加出厂设置并查看标记

Factory="System.ServiceModel.Activation.WebServiceHostFactory"

就像我设置的代码一样:

<%@ ServiceHost Language="C#" Debug="true" Service="PSICMS.EmailService1" CodeBehind="EmailService1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

【讨论】:

    【解决方案4】:

    试试这个:

    [WebMethod]
    public static string SendMail(string info)
    {
        return "";
    }
    

    这里的 info 有逗号分隔的值,你可以将它们分开使用。

    【讨论】:

      【解决方案5】:

      就调用该方法而言,一切看起来都很好。我假设您的方法路径不正确。当我使用这种方法时,[WebMethod] 将存在于同一页面的代码隐藏中,因此我将使用url: "Email.aspx/SendEmail 我还将向您的$.ajax 调用添加一个错误处理程序以帮助调试。在您的成功处理程序之后添加它。 error: function(a,b,c){alert(a.responseText);} 这应该告诉你问题是什么。您也不需要脚本管理器来完成这些工作。

      【讨论】:

        猜你喜欢
        • 2015-12-06
        • 1970-01-01
        • 2020-07-08
        • 1970-01-01
        • 1970-01-01
        • 2013-09-27
        • 2011-10-28
        相关资源
        最近更新 更多