How to use Ajax in MVC applications

Download Sample Application

In this post, I will discuss some basic building blocks of using Ajax or Async mechanism in MVC applications. I will not go into details about what is Ajax or what is Async mechanism. There are lot of good and informative books and posts about the topic.

MVC framework helps in providing mechanism of implementing Ajax features in your web applications. When you create a new web application, you will notice following lines in web.config file.

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
    

Notice setting of UnobtrusiveJavaScriptEnabled app setting value. This indicates to MVC framework that your application needs to include JS support for implementing Ajax or Async mechanims. Microsoft uses jQuery based implementation to accomplish this task.

For this discussion I have implemented a Contact Us page in web application. This page takes 3 input values from a user and then submits that information to server using Ajax. The following screenshot shows how this page looks like in my application.

Setting up model for the page

First set up model representing the information on the page for which you want to implement Ajax. For my application, I have created a very simple model object that contains these 3 pieces of the information.

public class ContactUsViewModel
{
  public string Name { get; set; }
  public string Email { get; set; }
  public string Message { get; set; }
}
    

Create Controller for page and ajax request

This is the important part of the implementation. We will need to set up controller and action that will be executed when client sends ajax request to server. And then server send appropriate response for client to render. I have created a ContactUsController for my page that serves default view for GET request and serves a different view after getting ajax request from client. Following snippet shows my simple set up. In your real application there will be more implementation when server receives data. This prototype shows how this all will be set up.

public class ContactUsController : Controller
{
  public ActionResult Index()
  {
   return View();
  }

  [HttpPost]
  public ActionResult Index(Models.ContactUsViewModel contactUs)
  {
   return View("ContactUsResponse", 200);
  }
}
    

Setting up Html form for Ajax in Mvc

Next step is to create views that we are going to server when user loads the page and then sends message.

@model MvcAsyncForms.Models.ContactUsViewModel
@{
    ViewBag.Title = "Contact Us";
    AjaxOptions ajaxOptions = new AjaxOptions()
    {
        UpdateTargetId = "messageresponse",
        Url = Url.Action("Index"),
        LoadingElementId = "sendingmessage",
        LoadingElementDuration = 3000,
        OnComplete = "onMessageSent"
    };
}
<div id="sendingmessage">
    <p>Sending your message .....</p>
</div>
<div id="messageresponse"></div>
<div id="contactUsForm">
    <h2>Contact Us</h2>
    @using (Ajax.BeginForm(ajaxOptions))
    {
        <table>
            <tr>
                <td><span>Name:</span></td>
                <td>@Html.EditorFor(m => Model.Name)</td>
            </tr>
            <tr>
                <td><span>Email:</span></td>
                <td>@Html.EditorFor(m => Model.Email)</td>
            </tr>
            <tr>
                <td colspan="2"><span>Message:</span></td>
            </tr>
            <tr>
                <td colspan="2">
                    @Html.TextAreaFor(m => Model.Message)
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <div style="text-align: center">
                    <input type="submit" value="Send Message" />
                    </div>
                </td>
            </tr>
        </table>
    }
</div>
<script type="text/ecmascript">
    function onMessageSent() {
        $('#contactUsForm').hide();
    }
</script>
    

There are two pieces in this view implementation. First you will need to set up AjaxOptions object that specifies all the ajax related options. You can see that we have set up following properties to indicate how we want to execute ajax request and how response will be rendered.

  • Url: This property sets up the POST url where requests will be sent
  • UpdateTargetId: This is HTML element that will be updated with response sent by server after processing ajax request
  • LoadingElementId: This is the HTML element that will be shown to user while ajax request is being executed and user is waiting for request to complete. This where you can show some message or some animation to indicate to the user that execution is in progress. This is a good practice that you should keep the users aware of progress of their request.
  • OnComplete: This is client side event triggers that when ajax request is completed. There are four events that are triggered for ajax request, OnBegin, OnComplete, OnSuccess and OnFailure. These allow you to handle various stages of ajax request so you can take action on client side accordingly. For demo purposes I have only handled OnComplete event where I am hiding request form after ajax request is complete.

There are more options that you can set in AjaxOptions class. I will discuss more advanced settings in subsequent posts. For this discussion I have only set most basic ones to get the job done.

Ajax.BeginForm

This is the place where you set up HTML form that will be used to send the data to server to execute your ajax request. There are about 12 overloads available for this method. I have used the most basic one that takes AjaxOptions as parameter to set up the request. In this block you will set up all the client side form that contains the data to be submitted to server.

Response for Ajax request

MVC framework makes it very easy for us to send us well formatted HTML response for any ajax request. And then it uses element represented by UpdateTargetId in AjaxOptions to display the response on client side. I have implemented a partial view that is sent back to client when ajax request is complete.

@model int
@{
    Layout = null;
}
@if (Model == 200)
{
    <span style="color: #00ff21; font-size: 1.2em;">Your message has been sent!</span>
}
else
{
    <span style="color: #f00;font-size: 1.2em">Your message could not be sent!</span>
}
<p>
@Html.ActionLink("Home", "Index", "ContactUs")
</p>
    

You can see how easy it is to implement Ajax in MVC web applications. In subsequent posts I will discuss more advanced details about the use of Ajax in MVC applcations.

Demo and sample code

You can see this in action at UniversalShoppingMall site that has been created using MVC4 with VS11. You can click on Contact Us link in top navigation and see how the ajax request works. The demo project included in this post is a simple stand alone implementation of this contact page.

comments powered by Disqus

Search

Social

Weather

7.2 °C / 45.0 °F

weather conditions Clouds

Monthly Posts

Blog Tags