ASP.NET WebMethods with jQuery and AJAX

I haven’t updated this blog in a long, long time, but today I was working on something interesting and thought I should write it down before I forget.

I was working on an ASP.NET application and needed to perform an AJAX request, I could have used the Microsoft AJAX framework, but frankly I don’t like it. Using the Microsoft ScriptManager element pulls in a lot of extra bloat that really isn’t necessary and the project was already using jQuery for animations. 
ASP provides these things called WebMethods (You’d probably be familiar with these if you’ve ever implemented a ASP.NET WebService), basically they’re a server side function that can be invoked similar to that of a REST API, a la Flickr.

Basically in your ASP.NET page code-behind file you just need to add a static / shared method that is decorated with a special WebMethod attribute.

VB.NET

<System.Web.Services.WebMethod()> _
Public Shared Function HelloWorld(ByVal name As String) As String
    Return String.Format("Hello world, meet {0}", name)
End Function

C#

[System.Web.Services.WebMethod]
public static string HelloWorld(string name)
{
    return string.Format("Hello world, meet {0}", name);
}

On the front end, I wrote a jQuery extension to consume these methods. This just needs to be included anywhere on the page.

jQuery(function ($) {    
    $.extend({
        webMethod: function (method, data, onSuccess, onFail) {
            var loc = window.location.href.split('?')[0];
            if (loc.substr(loc.length - 1, 1) == "/")
                loc = loc + "Default.aspx";
 
            // Serialize the data object with no whitespace 
            // (.NET requirement)
            var pairs = [];
            for (var i in data) {
                pairs.push(i + ':' + data[i]);
            }
            data = '{' + pairs.join(',') + '}';
 
            // Perform the post operation 
            $.ajax({
                type: "POST"
                , url: loc + "/" + method
                , 'data': data
                , contentType: "application/json; charset=utf-8"
                , dataType: "json"
                , success: onSuccess
                , error: function (jqXHR, textStatus, errorThrown) {
                    // The .NET error and stacktrace is hidden 
                    // inside the XMLHttpRequest response
                    if($.isFunction(onFail))
                        onFail($.parseJSON(jqXHR.response));
                }
            });
        }
    });
});

To invoke the above you’d do something like:

jQuery.webMethod('HelloWorld', { 
    name: 'Trent'
}, onSuccess, onFailure);
 
function onSuccess(data) {
    // The response from the function is in the attribute d
    alert(data.d);
}
 
function onFailure(data) {
    alert(data.Message + "\n" + data.StackTrace);
}

This will perform an AJAX request to the server and invoke your server side WebMethod.
If anyone has any comments or feedback, please let me know.

This entry was posted in .NET, jQuery. Bookmark the permalink.

7 Responses to ASP.NET WebMethods with jQuery and AJAX

  1. Troy Scheffel says:

    Very nice example! Easy-to-read, simple yet functional, and an elegant solution. Thanks!

  2. tony says:

    mate you forgot to add ‘static’ :
    public string HelloWorld(string name){…}

    should be:
    public static string HelloWorld(string name){…}

  3. shane says:

    In your C# example, you don’t declare the method as ‘static’. Also, I couldn’t get this to work. I received a 401 Unauthorzied – {“Message”:”Authentication failed.”,”StackTrace”:null,”ExceptionType”:”System.InvalidOperationException”}

    Any ideas why?

  4. mia says:

    very good example! Exactly what i was looking for! Thanks!

  5. siva says:

    Help me,
    When ever i call web method error function executes, here my code.

    var jsondata = “{‘rnoid':”+”‘”+rnoid+”‘”+”‘,name':” +”‘”+ name +”‘”+”,’gender':”+”‘”+gender+”‘”+”,’dob':”+”‘”+dob+”‘”+”,’qualification':”+”‘”+qualification+”‘”+”,’hobby':”+”‘”+hobby+ “‘”+”}”;
    jQuery.ajax({
    // url: “index.aspx/addDetails”,
    url: “PopupWebService.asmx/AddDetails”,
    type: “POST”,
    data: jsondata,
    contentType: “application/json; charset=utf-8″,
    dataType: “json”,
    success: function (data) {
    result=data.d;
    value = [result.Id, result.Name , result.Gender, result.Dob, result.Qualification, result.Hobby ];
    $(”, {
    id: innerid,
    “class”: ‘cinner’,
    }).appendTo(‘#outer’);
    for(i=0;i<6;i++)
    {
    $('’, {
    id: id[i],
    “class”: divclass[i],
    text: value[i]
    }).appendTo(“#”+innerid+””);
    }
    $(”,{
    id: (parentId+1),
    “class”: ‘userbtn’,
    text: “Edit”
    }).appendTo(“#”+innerid+””);
    $(”,{
    id: (parentId+2),
    “class”: ‘userbtn’,
    text: “Delete”
    }).appendTo(“#”+innerid+””);

    },
    error:function(){
    alert(” Error Try again later”);
    }
    });

    [WebMethod]
    public user AddDetails(string rnoid, string name, string gender, string dob, string qualification, string hobby)
    {

    list.Add(new user { Id = rnoid, Name = name, Gender = gender, Dob = dob, Qualification = qualification, Hobby = hobby });

    user data = list.Single(e => e.Id == rnoid);
    return data;
    }
    class user:

    public class user
    {
    private string id;

    public string Id
    {
    get
    {
    return id;
    }
    set
    {
    id = value;
    }
    }
    private string name;
    public string Name
    {
    get
    {
    return name;
    }
    set
    {
    name = value;
    }
    }
    private string gender;
    public string Gender
    {
    get
    {
    return gender;
    }
    set
    {
    gender = value;
    }
    }
    private string dob;
    public string Dob
    {
    get
    {
    return dob;
    }
    set
    {
    dob = value;
    }
    }
    private string qualification;
    public string Qualification
    {
    get
    {
    return qualification;
    }
    set
    {
    qualification = value;
    }
    }
    private string hobby;
    public string Hobby
    {
    get
    {
    return hobby;
    }
    set
    {
    hobby = value;
    }
    }
    }

    Thank in Advance.

  6. pat says:

    Looks like the Webmethod needs the string value to be wrapped in quotes eg.

    {name:’pat’}

    In my tests, the Webmethod would not accept your “serialised” code. What you send is actually


    {name:pat}

    which fails.

    Im using Windows 8.1 with Dot 4.5, so perhaps something has changed since the article was written.

  7. pat says:

    So the change to make this work for me is…

    pairs.push(i + ":'" + data[i] +"'");

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>