Basic AJAX with MVC3 & Razor

Suppose you have a page which requires you to load content inline in response to some action.  In the below example, you have a filter and a “preview” button which needs to show some sample data.

You could have the button do a post and have the MVC handler parse the form fields and render the view with the data you want to show.  But, you may have a complex page with many tabs and want to optimize form performance.    In such a case, you want to send just the form data for the current tab and inject the response into the current page.  Here is how to do that:

Here is the HTML of the relevant section of the “Export” tab:

<div class="btn green preview">
<a href="#">Preview</a></div>
<div class="clear"></div>
<div class="btn orange submit">
<a href="#">Export to CSV</a></div>
<div class="clear"></div>

Note the two href’s with attributes of btn.  Here is the relevant JavaScript:

$(document).ready(function () {
    $('.preview').click(function () {
        $.post('Home/Preview/?' + $(this).closest("form").serialize(), function (data) {
    $('.submit').click(function () {
        $('.submit a').html("Loading...");
        return false;

The “Export” button submits the entire form.  The “Preview” button on the other hand:

  1. Shows the “loading” text.
  2. Serializes the content of the parent form
  3. Posts the serialized content to a url
  4. Renders the response from that URL in the designated div

Here is Preview.cshtml:

    Layout =null;
@model  Models.ExportFilter
<strong>Name, Source, Email, DateAdded</strong>
    @foreach (var item in Model.MarketingList)
	<li>@item.FirstName, @item.Source, @item.Email, @item.DateAdded.ToShortDateString()</li>

Note that I am overriding the default Layout because I don’t want to show the normal header/footer. _Blank.cshtml contains solely “@RenderBody()”

The handler for the /Preview target is:

        public ActionResult Preview(ExportFilter filter)
            var export = new EmailExporter(filter);
            List emailList = export.Process();
            ViewBag.Message = string.Format("{0:##,#} records to be exported", emailList.Count); 
            return View(filter); 

Now when I click “preview”, I get a momentary “loading” screen and then the rendered view.

3 thoughts on “Basic AJAX with MVC3 & Razor”

Leave a Reply