ASP.NET MVC with Ajax - Ajax.BeginForm and PartialViews

The next Tampa ASP.NET MVC Developer Group Meeting is all about building a rich user interface with the ASP.NET MVC Framework: Introduction to jQuery with ASP.NET MVC, so I thought I would show off a quick example of how easy it is to use Ajax with the ASP.NET MVC Framework.

 

Microsoft.Ajax.js and MicrosoftMvc.Ajax.js

The first thing we want to do is add the Microsoft.Ajax.js and MicrosoftMvc.Ajax.js to our SiteMaster so we can leverage Microsoft ASP.NET Ajax in our simple ASP.NET MVC Web Application.

 

MicrosoftMvc.Ajax.js

 

Ajax.BeginForm

I then open up the Index View of the HomeController and change the view a bit to display a DropDownList of Customers in the Northwind Database within an Ajax.BeginForm(). The form will asynchronously post back and retrieve / display the details of the customer in a separate div tag, called customerDetails, just below the DropDownList.

 

Ajax.BeginForm()

 

The Index ActionMethod of HomeController retrieves all the Customers and places them in the ViewData to be populated in the DropDownList:

 

public ActionResult Index()

{

    var customers = _repository.FetchAll();

    ViewData["id"] = new SelectList(customers, "CustomerID", "ContactName");

    return View();

}

 

Details ActionMethod on HomeController

The Details ActionMethod on the HomeController returns a Partial View of the Customer Details for the Customer selected in the DropDownList:

 

public ActionResult Details(string id)

{

    var customer = _repository.FetchById(id);

    return PartialView("CustomerDetails", customer);

}

 

CustomerDetails PartialView

The CustomerDetails.ascx PartialView is just a slightly modified, Strongly-Typed Partial View of Customer:

 

PartialView ASP.NET MVC

 

ASP.NET MVC Ajax Sample Running

The end result is a simple ASP.NET MVC Ajax Sample that allows you to see the details of a Customer when you click the “Details” button. Everything is asynchronous and shows the simplicity of using ASP.NET Ajax with the ASP.NET MVC Framework:

 

ASP.NET MVC Ajax Sample Tutorial

 

Conclusion

If you are interested in developing rich user interfaces with the ASP.NET MVC Framework using ASP.NET Ajax and jQuery, check out the next Tampa ASP.NET MVC Developer Group Meeting - Introduction to jQuery with ASP.NET MVC.

 

David Hayden

 

ASP.NET MVC Book Reviews

 

posted on Tuesday, May 19, 2009 5:14 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices