Doing Ajax with the MVC Ajax Helper

Built into the MVC framework is the facility to make a form post with Ajax, and asynchronously update the page in response.

The Ajax Helper

If you have spent any time with Mvc, you are familiar with the HtmlHelper class. It usually shows up in code like Html.TextBox("Foo") in your views. Or perhaps you use Html.BeginForm() to create an Html form. To use the built-in Ajax stuff in MVC, you use another helper, the AjaxHelper.

The AjaxHelper helps you do Ajax in primarily two ways, by creating an Ajax form via a call to Ajax.BeginForm() or a call to Ajax.ActionLink(). The first creates a form that is posted back asynchronously, the second creates a link to perform an asynchronous get.

Don't forget to include the script files for MicrosoftAjax.js and MicrosoftMvcAjax.js! When you forget to add those, often you'll end up with a blank white page with only the Html fetched from the Ajax call.

The Ajax Link Helper

This is perhaps the simplest way to use the AjaxHelper class in MVC. The AjaxHelper's ActionLink method allows you to wire up links on the page for executing calls with Ajax. Note the following:

Add 30 Minutes to the Current Time

The current time plus thirty minutes: well...you have to click the link

The Code

    <p><%= Ajax.ActionLink("Add 30 Minutes to the Current Time", 
        "AddTime", 
        new { minutes = 30 }, 
        new AjaxOptions { UpdateTargetId = "ajaxTargetForLink" } )%>

The current time plus thirty minutes: <span id="ajaxTargetForLink" style="font-weight: bold;">well...you have to click the link

The Ajax Form Helper

So let's look at a simple example of the AjaxHelper's capabilities for Ajax'n up a form.

The current time plus the value above is as follows: Fill in the form, yo...

The Code

        <% using (Ajax.BeginForm("AddTime", 
            new AjaxOptions { UpdateTargetId = "ajaxTarget" }))
           { %>
            
<%= Html.TextBox("Minutes")%>
<% } %>

The current time plus the value above is as follows: <span id="ajaxTarget" style="font-weight: bold;">Fill in the form, yo...

The most pertinent points are the following:

  • Note that the first argument of the Ajax.BeginForm call is to the method being invoked for the ajax functionality.
  • Next are the options, the most important of which (and the only one required in this situation) is the id of the element of which the contents are going to be updated.
  • Note that the form itself is just like any other form you would build with MVC.
  • The target, the last piece of markup, is the span marked with the id "ajaxTarget".