Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MVC Framework and jQuery = Ajax Heaven

DZone's Guide to

MVC Framework and jQuery = Ajax Heaven

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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:

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

 

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Mike Hadlow, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}