I need to get into the habbit of posting more to my blog. As such, I thought I'd make a short post about how to do simple Ajax calls in MVC to get data from the server. Before continuing, if you're not familiar with MVC and JQuery, I'd suggest working on those skills first.

We're going to be using a SQL database for this example, along with the Entity Framework as our ORM.

What you'll need

  1. Visual Studio with some version of MVC installed
  2. SQL Server 2008 or above
  3. JQuery set up
  4. JQuery UI set up
  5. JQuery UI Dialog plugin installed

Sample Database

We'll use a simple database composed of Items and Categories. Items belong in zero or more more categories. Our database will look like this:

 

Relevant Controller Actions

First we start with a base controller, so all other controllers can use common resources.

using FunWithAjax.Models;

namespace FunWithAjax.Controllers
{
    public class FunWithAjaxController : Controller
    {
        protected FunAjaxEntities db = new FunAjaxEntities();
    }
}

Our Item controller's Index action will have IEnumerable<Item> pass to it's view.

namespace FunWithAjax.Controllers
{
    public class ItemController : FunWithAjaxController
    {
        public ActionResult Index()
        {
            return View(db.Items.ToArray());
        }
    }
}

Our Item view will have a fairly straight-forward listing of all items in the db.

 

Notice we added an extra attribute "data-item-id". This will be important later. Now when we compile, we get a list of items:

In our Home controller, we have the action that returns the partial view we want to render when looking at a specific item.

        [HttpGet]
        public ActionResult Jump(int? itemID)
        {
            return Jump(itemID, null);
        }

        [HttpPost]
        public ActionResult Jump(int? itemID, FormCollection formCollection)
        {
            Item item = db.Items.Where(i => i.ID == itemID).FirstOrDefault();
            if (formCollection == null)
            {
                return PartialView("JumpModal", item);
            }

            return View();
        }

And our partial view for the item details:

 

Finally, the Ajax request:

$(document).ready(function () {

    $('a#jump-link').click(function () {
        var itemID = $(this).attr('data-item-id');
        var itemName = $(this).html();
        $('#dialog').dialog({
            title: itemName,
            autoOpen: true,
            width: 400,
            height: 500,
            modal: true,
            open: function (event, ui) {
                $(this).load("/Home/Jump?itemID=" + itemID);
            },
            buttons: {
                "Close": function () {
                    $(this).dialog("close");
                }
            }
        });
    });

});

This reads like the following: When clicking a link, grab the id and name from the element, then use the dialog function to open a dialog. The key part is open function. Here we want to load directly from the details link.

What we end up with is much nicer than refreshing the page when we want to look at item details!