Unobtrusive Ajax helpers in MVC3

ASP.NET MVC has included Ajax helpers since its first release. These allow you to generate “ajax-enabled” html elements, such as hyperlinks or forms that submit data asynchronously. For example, you can use the Ajax.BeginForm method to construct an ajax-enabled form:

<% using (Ajax.BeginForm("Save", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "#myDiv" })) { %>
<% } %>

This would generate markup like this:

I never particularly liked these helpers – firstly, they required your page to include the MS-Ajax clientside library and secondly they defined inline javascript which goes against the unobtrusive javascript principle. In the end, there isn’t really a compelling reason to use them over something like jQuery.

However, in ASP.NET MVC 3 these helpers have been significantly improved. They no longer rely on the MS-Ajax client libraries to do their work – instead they use jQuery and the unobtrusive jQuery extensions that ship with MVC3. They also use HTML5 data- attributes to annotate a particular element with metadata rather than defining inline scripts.

The above example now generates the following markup with MVC3:


So long as you have both jQuery and the jQuery.unobtrusive-ajax scripts included then this form will automatically be “hijaxed” and use javascript to submit the form if it’s enabled. Overall, a big improvement over the ajax helpers in MVC2.

Written on December 27, 2010