Simple Introduction to MVC Ajax (ASP.NET MVC 5)

14/09/2014

The jQuery Ajax built into ASP.NET MVC is very powerful but it's hard to know exactly where to start. This tutorial is a result of a few hours investigation so it's written from the point of view of a beginner.

I intend to upload code samples at some point but I need to add a code hosting feature to my website.

Setting up our test environment

We're going to use a very simple example to work with only the details we need. As always we're using a dog class, here's a picture of a dog:

A picture of a dog.

The first thing we need to do is set our project up with Ajax. Right click your project and open the Nuget Package Manager. Search for "Ajax" and install the Microsoft jQuery Unobtrusive Ajax package.

Install the Microsoft jQuery Unobtrusive Ajax package

This adds the jquery.unobtrusive-ajax.min.js file to our Scripts folder. We need to include this in our webpage. The easiest way to do this is to add it to our BundleConfig class (in the App_Start folder):

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
           "~/Scripts/jquery-{version}.js", 
           "~/Scripts/CustomScripts/StickyFooter.js",
           "~/Scripts/jquery.unobtrusive-ajax.min.js"));

This should be included in your master _Layout page using @Scripts.Render("~/bundles/jquery").

Creating a test page

With the following dog class:

public class Dog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
}

And the following controller method (DogController.cs):

public ActionResult Details()
{
    Dog dog = new Dog{Id = 7, Name = "Lord woofington",
        BirthDate = new DateTime(year: 2005, month: 06, day: 27)};
    return View(dog);
}

We can quickly get a view to work with. Before we can navigate to the action we need a view. This is the view the Wizard created for the Dog class in Views/Dog/Details.cshtml:

@model JunkCode.Dog
<h2>Dog Details</h2>
<div>
    <dl class="dl-horizontal">
        <dt>@Html.DisplayNameFor(model => model.Name)</dt>
        <dd>@Html.DisplayFor(model => model.Name)</dd>
        <dt>@Html.DisplayNameFor(model => model.BirthDate)</dt>
        <dd>@Html.DisplayFor(model => model.BirthDate)</dd>
    </dl>
</div> 

Our first simple Ajax call

The simplest thing we can do is call a controller method using an ActionLink. We add the following code to our view:

@Ajax.ActionLink(linkText: "Call An Action", 
                    actionName: "Bark", 
                    ajaxOptions: new AjaxOptions { UpdateTargetId = "ajaxtarget", 
                                                    InsertionMode = InsertionMode.InsertAfter })

<div id="ajaxtarget"></div>

Some points:

  • Named parameters using [text]: have been a feature of Visual Studio since 2010 and are a nifty little feature to make your code more readable.

  • This ActionLink presents a link with the given linkText and when clicked calls the Action (given by actionName) on the Dog Controller.

  • The AjaxOptions allow you to modify the exact behaviour of the Ajax call.

We then need an Action on our Controller for our link to actually call:

public string Bark(){ 
    return "Woof!"; 
}

When we click this the text "Woof!" is added to our ajaxtarget div. Clicking repeatedly appends the text to our div.

Calling the Action repeatedly results in 'Woof!Woof!Woof!' written to screen

Next Post

This is pretty nifty, but what else can we do?

Go to the Next Post to find out about using PartialViews and Ajax Forms.