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

时间:2009-05-20 08:52:54

标签: asp.net jquery web-services asmx

我正试图通过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成功方法。可能导致这种情况的原因是什么?`

5 个答案:

答案 0 :(得分:37)

要调用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/

编辑:扩展名不会更改为.asmx,但仍为.aspx。

答案 1 :(得分:9)

看起来你正在尝试使用页面方法。

在这里Page Methods in ASP.NET Ajax寻求帮助

答案 2 :(得分:2)

您应该使用Web服务而不是常规的aspx网页。网页不支持调用Web方法,我相信您的jQuery请求会加载HTML页面。我建议你做两件事:

  1. 使用Fiddler2(使用IE)或HttpFox(使用Firefox)在客户端调试AJAX请求和响应。
  2. 在服务器端使用WCF Web服务。在这种情况下,您可以使用SvcConfigEditorSvcTraceViewer在服务器端配置和调试Web方法。

答案 3 :(得分: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中添加它。

答案 4 :(得分: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方法回调

的直接方式的人来说,它非常适用