Calling an ASP.NET server side method via jQuery

I'm trying to call a server side method from client side via jQuery. My code is as follows:

Server side:

    using System.Web.Services;
    [WebMethod()]
    //[ScriptMethod()]
    public static void SendMessage(string subject, string message, string messageId, string pupilId)
    {
        //Send message
    }

Client side:

$("#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;
});

I've added a break point on the server side SendMessage method, but it's never hitting it, but when I run the code the jQuery success method is called. What could be causing this?`


Solution 1:

To call ASP.NET AJAX "ScriptServices" and page methods, you need to use the full $.ajax() syntax:

$.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.
  }
});

See this post for details on why that's necessary: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Edit: The extension doesn't change to .asmx but remains .aspx.

Solution 2:

It looks like you're trying to make use of a page method.

Take a look here Page Methods in ASP.NET Ajax for help

Solution 3:

You should use web service instead of regular aspx web page. Web pages has no support to call web methods, I believe your jQuery request loads the HTML page instead. I suggest you two things:

  1. Use Fiddler2 (with IE) or HttpFox (with Firefox) to debug AJAX requests and responses on client side.
  2. Use WCF web service on the server side. in this case you can use SvcConfigEditor and SvcTraceViewer to configure and debug web methods on the server side.

Solution 4:

$.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); }  
     });

If this doesn't work...and gives "Syntax Error: syntax error"...then add this

<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>

between </compilation> and </system.web> in your Web.Config file.

Hope this will help somebody because took me a while to figure that beside jquery function i have to add that in Web.Config.

Solution 5:

Here is code that might work in your situation.

<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);  
      }  

There is an example that has always work for me.

Here is the complete article http://www.webdeveloperpost.com/Articles/How-to-use-jquery-ajax-in-asp-dot-net-web-page.aspx

It works well for those that want a straight forward way of using the jquery asp.net method call back