通过jQuery调用ASP.NET服务器端方法

35
我想从客户端通过jQuery调用服务器端方法。我的代码如下:
服务器端:
    using System.Web.Services;
    [WebMethod()]
    //[ScriptMethod()]
    public static void SendMessage(string subject, string message, string messageId, string pupilId)
    {
        //Send message
    }

客户端:

$("#btnSendMessage").live("click", function(){
  var subject = $("#tbSubject").val();
  var message = $("#tbMessage").val();
  var messageId = $("#hdnMessageId").val();
  var pupilId = $("#hdnPupilId").val();

  $.ajax({
      type: "POST",
      url: "./MessagePopup.aspx/SendMessage",
      data: ("subject=" + subject + "&message=" + message + "&messageId=" + messageId + "&pupilId=" + pupilId),
      error: function(XMLHttpRequest, textStatus, errorThrown){
          alert(textStatus);
      },
      success: function(result){
         alert("success");
      }
   });
   return false;
});

我已经在服务器端的SendMessage方法上添加了断点,但它从未触发,但当我运行代码时,jQuery的success方法被调用。这可能是什么原因?


SendMessage内的代码没有运行,还是您只是无法调试它? - Amr Elgarhy
SendMessage代码既无法运行,也无法进行调试。 - Fermin
你的服务器端方法确实是一个 ASPX 页面而不是 ASMX 或 WCF Web 服务吗?URL 指向 aspx 网页。 - Artem Koshelev
是的,我的服务器端方法位于 ASPX 页面内,我应该创建单独的 ASMX 或 WCF Web 服务吗? - Fermin
5个回答

38

要调用ASP.NET AJAX的"ScriptServices"和页面方法,需要使用完整的$.ajax()语法:

$.ajax({
  type: "POST",
  url: "MessagePopup.aspx/SendMessage",
  data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

详情请参见此帖子:http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

编辑:扩展名不会改变为.asm x,而保持为.aspx。


4
明白了,这段代码的唯一差别在于网址是MessagePopup.aspx,而不是asmx。谢谢大家。 - Fermin
@Dave Ward:非常感谢您提供的可以直接运行的示例! - delliottg
请问您能否提供一些关于我的问题的见解:http://stackoverflow.com/questions/41752213/why-is-asmx-giving-an-error-when-pulling-data-using-client-script。谢谢。我的是一个`.asmx`文件。 - Si8

9

我不知道Page Methods +1。 - Jose Basilio

2
$.ajax({  
        type: "POST",  
        url: "MessagePopup.aspx/SendMessage",  
        data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",  
        async: true,  
        cache: false,  
        contentType: "application/json; charset=utf-8",  
        dataType: "json",  
        success: function() {},  
        error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); }  
     });

如果这个方法不能正常工作,且显示“语法错误:语法错误”时,请添加以下内容。
<httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" validate="false"/>
        </httpHandlers>
        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </httpModules>

在您的Web.Config文件中,</compilation></system.web>之间。希望这可以帮助某些人,因为我花了一些时间才发现除了jQuery函数之外,我还必须在Web.Config中添加它。

2
您应该使用Web服务而不是常规的aspx网页。网页没有支持调用Web方法,我相信您的jQuery请求会加载HTML页面。我建议您两件事情:
  1. 使用Fiddler2(与IE一起使用)或HttpFox(与Firefox一起使用)在客户端调试AJAX请求和响应。
  2. 在服务器端使用WCF Web服务。在这种情况下,您可以使用SvcConfigEditorSvcTraceViewer来配置和调试Web方法。

为什么你说WCF而不是ASMX? - Fermin
WCF现在是.NET的主要和推荐通信技术。它比asmx web服务具有更多的功能,具有更好的可测试性(Google搜索“Unit testing WCF services”)。 从战略上讲,学习WCF是一个正确的选择。查看此帖子以了解有关asmx vs WCF的更多信息: http://social.msdn.microsoft.com/Forums/en-US/dotnetstocktradersampleapplication/thread/048d8a45-dad8-431f-886c-9aae78862285 - Artem Koshelev
另外,您可以查看微软的性能基准测试:http://msdn.microsoft.com/en-us/library/bb310550.aspx - Artem Koshelev

1

这里是一段可能适用于您情况的代码。

<script type="text/javascript">
    $(document).ready(function () {

        // Add the page method call as an onclick handler for the button.
        $("#btnSubmit").click(function () {

            //get the string from the textbox
            $.ajax({

                type: "POST",
                url: "testSearch.aspx/GetMyShippingDate",
                contentType: "application/json; charset=utf-8",
                data: "{'tracking_num': '" + $("#txtTrackingNumber").val() + "'}",  
                dataType: "json",
                success: function (date) {

                    // Replace the div's content with the page method's return.
                    Success(date);

                },
                error: Failed
            });
        });
    });

     function Success(result) {  
          $("#ParcelShippingDate").html(result.d);
      }  
      function Failed(result) {  
          alert(result.status + " " + result.statusText);  
      }  

这里有一个一直对我有效的例子。

以下是完整文章http://www.webdeveloperpost.com/Articles/How-to-use-jquery-ajax-in-asp-dot-net-web-page.aspx

对于那些想要直接使用jquery asp.net方法回调的人来说,它非常有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接