Friday, October 31, 2008

MVC Framework and jQuery = Ajax heaven

I've got an admission to make: I've never used any of the Microsoft Ajax Toolkit. But recently I've been adding some mapping functionality to the project I'm working on. We wanted users to be able to pull a marker to a position on a map and have the new position updated on the server. Obviously we were going to have to use Ajax of some kind to do that. What I want to show today is how trivially easy it's proved to be to use MVC Framework on the server and jQuery on the browser to do Ajax requests and updates. JQuery is now included in the default project for the MVC Framework, so there's no excuse not to use it.

Here's a very simple scenario. I've got a a page where I want to show a list of people when I click 'Get People'. I also want to add a person to the database when I type their name into a text box and click 'Add Person'. Here's what it looks like:

AjaxDemo

The first thing we do is create the button for 'Get People' and an unordered list to put the people in:

    <input type="button" id="getPeople" value="Get People" />
    <ul id="people_list">         

Next we have a jQuery ready handler (which fires when the page loads) that sets up the event handler for the getPeople button:

$(function() {
    $("#getPeople").click(function() {
        $.getJSON("/Home/People", null, getPeople);
    });
});

When the button is clicked we fire off a json request to /Home/People. This maps to a People action in our Home controller:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult People()
{
    var db = new DataClasses1DataContext();
    return Json(db.Persons);
}

All we do here is get all our Person records (using LINQ to SQL) and return them as Json. When the response is returned to the browser the getPeople callback function is called. Remember we set this in the getJSON jQuery method above. Here's the getPeople function:

function getPeople(people) {
    $("#people_list").text("");
    $.each(people, function(i) {
        $("#people_list").append("<li>" + this.Name + "</li>");
    });
}

The callback provides the data returned from the JSON request as its argument. All we have to do is use the handy jQuery each function to iterate through our people collection and append a new li element to our list for each one. The really nice thing here is how well the MVC Framework and jQuery interact. I didn't have to do any conversions between them. Our data just automagically converts from C# objects to Javascript.

How about the update? This is just as simple. First we need some more HTML: a text box to type the name into and a button to fire the update:

    <label>Name <input type="text" id="name" /></label><br />
    <input type="button" id="addPerson" value="Add Person" />

Next another click event handler is set up to handle the addPerson click event:

$("#addPerson").click(function() {
    var name = $("#name")[0].value;
    if (name == "") {
        alert("You must provide a name");
        return;
    }
    var person = { Name: name };
    $.post("/Home/People", person, null, "json");
});

This time we use the useful 'post' function to post our newly created person JSON object to the /Home/People URL. Because this is a POST request it's handled by our overloaded People action, this time attributed with AcceptVerbs[HttpVerbs.Post]:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult People(string Name)
{
    var db = new DataClasses1DataContext();
    var person = new Person {Name = Name};
    db.Persons.InsertOnSubmit(person);
    db.SubmitChanges();
    return null;
}

All we have to do to retrieve the Name of the person is to name the argument of the action 'Name'. The MVC Framework automatically pulls apart the request, finds a value called 'Name' and supplies it to the action. If you have a complex JSON structure you can deserialize it to a C# object using the built in data binding. All that's left to do is create a new Person instance with the given name and save it to the database. Nice!

I'm a latecomer to the Ajax party, but with jQuery and the MVC Framework I'm finding a breeze to wire up some pretty nice functionality.

You can download the demo solution here:

http://static.mikehadlow.com/JQueryAjax.zip

4 comments:

LYFE4nWo said...

Very good example. I was wondering how json works with MVC, but this really gave me a good understanding. Kudos to you!

Mike Hadlow said...

Hi LYFE4nWo,

Glad you found it useful.

Gopinath said...

Superb article. I was able to quickly understand how to use JQuery with MVC.

Anonymous said...

Great stuff! I'd done a little AJAX under web forms but this makes it very easy to transition and the jquery is cool. Thanks for the example!