I strongly dislike synchronous browser requests: the request has to be sent to the server, server action is performed, a server response is received, and the page is re-rendered which usually involves reloading images, style sheets, JavaScript files, etc. It takes time, sends an awful lot of traffic across the wire, and it doesn’t provide for the best user experience. In some scenarios this makes sense, but in most cases I find it to be an annoyance.
Enter jQuery to the rescue. jQuery is the most exciting innovation to happen to JavaScript since, well, maybe JavaScript itself. One of the jQuery features I enjoy the most is the AJAX functionality which allows jQuery to talk to the server asynchronously, or behind the scenes.
I personally like to use the JSON (JavaScript Object Notion) format, which is lighter-weight than XML. Using jQuery, a JSON GET request is written as:
$.getJSON('[url]', { [parameters] }, function(json) {
// callback function code
});
Let’s say I want to perform an asynchronous search in my web page for people names without having to reload the page. In MVC, I need an action to handle the request:
public class SearchController : Controller
{
string[] peopleNames = new[] { "Bob", "Steve", "Joe", "Frank", "Lou" };
public JsonResult Search(string q)
{
var results = peopleNames.Where(n => n.Contains(q));
if (results.Count() > 0)
return new JsonResult { Data = new { Success = true, Results = results } };
else
return new JsonResult { Data = new { Success = false } };
}
}
The first thing to notice is the built-in JsonResult type on the Search action. MVC understands and is able to handle JSON data. Simply return a JsonResult object and populate the Data property with the data to be returned. The serialization of that data is handled under the covers.
Back in the MVC View, call getJSON to make a request to the action and handle the response:
$.getJSON('<%= Url.Action("Search", "Search") %>', { q: $('input#search') }, function(json) {
if (json.Success) {
// results found
}
else {
// nothing found
}
});
Note that
Url.Action is used to get the virtual url.
Url.Action and
Url.Content are great ways to handle relative paths. Next, the search query is passed from an input field with an ID of search. And finally, the callback is handled. jQuery handles the deserialization under the covers, and the values can be handled as simple properties.
The introduction of ASP.NET MVC and jQuery make asynchronous calls very quick and easy, and help to provide the end user with a better experience. In future posts, we’ll look at more specific examples of utilizing jQuery and MVC to provide a better user experience.