Monday 4 July 2011

Simple jQuery AJAX example calling a MVC controller

If you can't see the syntax highlighting in your feed reader (i.e. Google reader) please open the link in your browser.

In this post I will outline a very simple AJAX call to an MVC controller object using jQuery and JSON.

Lets start with the front-end code. Below is a simple HTML input and anchor tag:



Find


When a user enters an image ID in the in the text box and clicks on the find link we will send an AJAX request using jQuery and sending JSON data to the MVC controller. The JSON helper object below is explained here. Below is the JavaScript code:

$(".findLink").click(onFindClick);

function onFindClick(e) {
var jsonData = { imageId: escape($("#ImageId").val()) };

$.ajax({
        type: "POST",
        url: "/Controllers/ImageManager/FindImage",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(jsonData), // Convert JavaScript object into a JSON object string.
        dataType: "text json",
        success: function (XMLHttpRequest, textStatus, data) {
            var jsObj = jQuery.parseJSON(data.responseText); // Convert JSON object into a JavaScript object.

            if (jsObj != null) {
                alert("JSON result = " + data.responseText);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("There has been an error: " + errorThrown + " - " + textStatus + " - " + XMLHttpRequest.statusText);
        }
    });
}


Now for the MVC controller:

public class ImageManagerController : Controller
    {
        public string FindImage(string imageId)
        {
            // Do some code to get the image object...
// Assume image object has 2 properties: Id and Url.
            return SerializeNode(image);            
        }
}

        private static string SerializeNode(ImageReference imageRef)
        {
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var simple = new { Exists = imageRef != null, Id = imageRef != null ? imageRef.id : 0, Url = imageRef != null ? imageRef.Url : "" };
            return serializer.Serialize(simple);
        }


Hope this helps. A very brief example but should outline the major points.

No comments: