Pseudorandom Knowledge

Ajax via jQuery and ASP.NET

In this simple example of Ajax we will create a text field and a button. When the button is pressed the text should be sent to the server where it is upper cased and returned. The result is then displayed to the user.

<h2>Upper case</h2>
<p>
    <input id="input" type="text" />
    <input id="button" type="button" value="DO IT" />
</p>
<p>
    <span id="output"></span>
</p>

In ASP.NET MVC

To receive and process the text in MVC we create a controller method. Don’t forget to make a route for it as well.

[HttpPost]
public JsonResult Uppercase(string text)
{
    return Json(new { Text = text.ToUpper() });
}

Here we use a rather nice feature of MVC. If the controller method takes any parameters MVC will search in several places for a value to populate that parameter with. In our case the text parameter will be found in the query string but it could also have been in the routing data, posted form values or sent as JSON from the client.

After processing we use JSON to return data to the client. Here I’m using an anonymous type but you can use JSON to serialize any object. Because returning JSON in a GET request is a security risk we limit the method to POST requests. MVC will actually not allow us to use GET together with JSON, if you do it will just fail silently.

$("#button").click(function () {
    $("#output").html("processing...");
    $.ajax({
        type: "POST",
        url: "uppercase",
        data: { text: $("#input").val() },
        success: function (response) {
            $("#output").html(response.Text);
        }
    });
});

This is the code we write on the client side to call the server method. When the button is pressed we first write out a message to the user in order to give immediate feedback. If we don’t do this and the server is slow it may seem like the button didn’t do anything. You may also want to disable the button until the request finishes depending on the situation.

To make the actual call we use the ajax method in jQuery. The type and url parameters are hopefully self explanatory. For the data parameter we give it a JavaScript object, jQuery will convert this to a query string for us. The success function is called when the call returns, remember that this is an asynchronous call. The JSON is automatically parsed for us and passed to the function.

In ASP.NET Web Forms

To do the same thing in Web Forms we can use a rather nice feature called web methods. In my case I have put this in the code behind file for the web page but you could put it in a web service instead.

[WebMethod]
public static object Uppercase(string text)
{
    return new { Text = text.ToUpper() };
}

This looks rather similar to the method we used in MVC but there are two differences. The data we return here is returned as JSON but implicitly instead of explicitly. Secondly the data sent to this method must be in JSON format. Using a query string will not work. Note that the return value in my case is object only because I return an anonymous type, it could have been anything.

$("#button").click(function () {
    $("#output").html("processing...");
    $.ajax({
        type: "POST",
        url: "Page.aspx/Uppercase",
        data: JSON.stringify({ text: $("#input").val()}),
        contentType: "application/json; charset=utf-8",
        success: function (text) {
            $("#output").html(text.d.Text);
        }
    });
});

The client side code is mostly the same as for MVC. Notice how the URL looks when calling a web method. The biggest change though is that we have to send the data as JSON. To do this we have to set the content type and create the JSON string ourselves. The method I’m using to create the JSON string is not part of jQuery, it is a native method in modern browsers. If you want to support older browsers you need to include the JSON2 library.

There is also a small puzzling change here. We have to include an extra .d when getting the returned data. This is a security feature that prevents certain XSS attacks.

Web Forms the hard way

If you for some reason don’t want to use web methods you could use the following code. Put it in the page load method of the page you’re calling.

if (Request.Params["Callback"] == "uppercase")
{
    string text = Request.Params["Text"];
    JavaScriptSerializer s = new JavaScriptSerializer();
    string response = s.Serialize(new { Text = text.ToUpper() });
    Response.ContentType = "application/json";
    Response.Write(response);
    Response.End();
}

Call this with Page.aspx?Callback=uppercase and send the data as a query string.