in

Dé specialist in .NET trainingen en consultancy

Erik van Appeldoorn

september 2009 - Posts

  • Using AJAX in ASP.NET MVC

    I really like the ASP.NET Model-View-Controller web application template. It takes so time to get used to ASP.NET MVC but the benefits are great: The strict separation of mark-up (views) and logic (Controllers) leads to a clear structure of your application and makes it really easy to add unit testing.

    At this moment there are no native controls from Microsoft for ASP.NET MVC. So there is no such thing as a MVC UpdatePanel. But there is native support for AJAX using ASP.NET.MVC.

    To get started:

    1. You have to add two references to your SIte.Master.

    <script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" type="text/javascript"></script>  
    <script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>" type="text/javascript"></script>

    The scripts are part of the ASP.NET MVC 1.0 template, they are just not included in the master page by default.

     

    2. In your views you can make use of partial rendering using the AJAX helper class. It works pretty much the same as the MVC HTML Helper.

    So for example there is an AJAX.ActionLink method. Like the HTML.ActionLink method you can use it to point to a specific action of a controller. But next to this there is an extra parameter which accepts an object of the AjaxOptions class. Using the UpdateTargetID property of this class you can define which element on the view has to be updated with the result of the action.

     

    So for a quick demo of partial rendering using the AJAX helper class, add the following lines in your view:

    <span id="Result">Empty</span><br />

    <%= Ajax.ActionLink("Click here..", "DoAJAXAction", new AjaxOptions { UpdateTargetId="Result"} %>

    Now create an DoAJAXAction method in the controller, like this:

    public ActionResult DoAJAXAction()
    {
         return Content("Updated at" + DateTime.Now.ToLongTimeString());
    }

    This is just a basic example to get you started. If you are interested in more details please take a look at the MSDN documentation.

    http://msdn.microsoft.com/en-us/library/system.web.mvc.ajaxhelper.aspx