Using jQuery & JSON with ASP.NET

There was a recent post on Encosia about how to use jQuery to interact with web services. In this article I will expand on a couple of the points and add a few new wrinkles

Creating the Web Service

The first thing that we need to do is to define our web service. I am using ASP.NET Web Services (ASMX) here, but you could also use WCF if you are using .NET Framework 3.5. The Updater web service will define one method called UpdateItem that will take an item ID to update, although you could just as easily create a method that will take any number of parameters.

One thing to notice is that I am doing a try-catch where I check for 2 separate exceptions. The first, UserInputException is a user-defined exception that is throw whenever we encounter a known error. This allows us to display a safe error message to the user for expected conditions. For any unexpected Exceptions, we catch a generic Exception and then throw a new Exception with a boilerplate error message. This will be thrown to the javascript where we can just display the error message. As always, we only want to show the user our pre-defined error messages. If we have an unexpected error, we do not want to show the error message to the user.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Updater : System.Web.Services.WebService
{
    [WebMethod]
    public string UpdateItem(string itemID)
    {
        try
        {
            DataLayer.UpdateItem(itemID);
            return "The Item has been updated";
        }
        catch (UserInputException uie)
        {
            // We expect this exception and they are defined error messages to display
            throw uie;
        }
        catch (Exception)
        {
            // This is an unexpected error that we would log and display a generic error message for
            throw new Exception("Sorry an error has occurred updating the data.");
        }
    }
}

Calling the Web Service

There are a couple of things to notice in the jQuery that calls the web service. We are setting contentType to “application/json; charset=utf-8″ so that we can use JSON to talk to our web service. Since we are posting data this is ok, but if this was simply a request we would need to set the beforeSend parameter to set the request header. This is shown in the Encosia article that I linked to earlier.

We are also using the JSON2 script to convert our string to JSON and to convert our response to JSON. This is a more secure approach than simply using eval. JSON2 parses the jQuery to create the object, while eval simply executes the random code to create the object. Eval is certainly much simpler, but is far less secure, so don’t be lazy - parse your JSON into objects.

Our JSON page has a function for both success and error, but I will be focusing mostly on the error function here. It takes 3 parameters, but the first parameter, which is an XmlHttpResponse JSON response, is the only parameter we will be using. We will use JSON.parse to get our response from the JSON and if we have a message we will display it. This message is the message of the exception that was thrown in our Web Service. You can see why it is useful to define all of our error messages on the server side so that we can just display them here without any extra effort. Let me again stress that you should make sure that all of your exceptions have been caught and given a safe error message. You should not be showing arbitrary exception messages to the user.

function updateItem()
{
    $('#update_link').click(function(){
        // Get the item id from the box and format the JSON
        var itemID = {"itemID" : $('#ItemId').val()};
        var jsonStr = JSON.stringify(itemID);

        // Call our Web Service, passing in our JSON params. The error function is called
        // whenever an exception is thrown by the web service (among other times)
        $.ajax({
          type: "POST",
          url: "Updater.asmx/UpdateItem",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          data: jsonStr,
          success: function(msg){
            $('#update_box').prepend('‘ + msg.d + ‘‘);
          },
          error: function(xhr, msg){
            var response = JSON.parse(xhr.responseText);
            if(response.Message)
            {
                $(’#update_box’).prepend(’‘ + response.Message + ‘‘);
            }
            else
            {
                $(’#update_box’).prepend(’There was an unknown error calling the Web Service‘);
            }
          }
        });
        return false;
    });
}

Conclusion

Using jQuery’s Ajax method provides a clean syntax to interact with ASP.NET Web Services. While there are a couple of things that you need to pay attention to, it is really fairly simple to do. I won’t go over all of the advantages of using jQuery instead of ASP.NET Ajax, but there are plenty. I find it much easier to separate the layers of my application when using jQuery, as ASP.NET Ajax tries to tie deeply into the ASP.NET framework.

Download Solution

2 Responses to “Using jQuery & JSON with ASP.NET”

  1. Faraz Says:

    Great article man, I’ve seen so many similar articles, but this article covers everything. Would you please show me how to post multiple variables to the web service using JSON.stringify and jQuery. I’m having a hard time to do that?

    For example, what would the code be like if I wanted to send a productId beside the itemId. Basically, send two variables to the web service instead. Thanks

  2. Keith Says:

    You can change your WebMethod signature to be something similar to this:
    public string UpdateItem(string itemID, int productID)

    In terms of the javascript, you could change the string to be something like this:
    var inputStr = {itemID : $(’#ItemId’).val(), productID : 5};
    var jsonStr = JSON.stringify(inputStr);

Leave a Reply