ASP.NET MVC QuickStart 8: partial updates using jquery

…continued from part 7.

Objectives

In this Hands-On Lab, you will learn how to do partial updates in JSON format using jquery. In particular, you will:
- Task 1: add new controller action and view
- Task 2: add controller action method to get list of members
- Task 3: add jquery to populate members combo box
- Task 4: show member details

System requirements

You must have the following items to complete this lab:
- Microsoft Visual Studio 2008 SP1 (professional edition)
- Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:
- Fundamental knowledge of software development in .NET 3.5
- Some experience in ASP.NET web development
This lab builds further on the QuickStart 7 code.

Task 1: add new controller action and view

We are going to create a new page that has a combo box containing all member last names, and the details of the selected member. First add a new controller action to the MembersController:

public ActionResult Index2()
{
// return this list to the default view
return View();
}

Also add a view for this action method:

Add View

In this case we are not going to create a strongly typed view because the needed data will be retrieved asynchronously using jquery.

Modify the generated view. First, place a combo box in the view:

 

<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
runat="server">
Index2
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
runat="server">
<h2>Index2</h2>

<% <select id="MembersDropDownList" />
</asp:Content>

To fill this combo box with members using AJAX, we have to:

  • Add a controller action method that returns a list of members
  • Write some jquery that uses the controller action method to populate the combo box when the page has been rendered

We will do this in the next tasks.

Task 2: add controller action method to get list of members

Add a new action method called GetCustomers to the MembersController:

public JsonResult GetMembers()
{
// Get a list of members using the model
List<Member> members = MemberService.GetMembers();

// Return list of members as JSON
return this.Json(members);
}

As you see this method returns a different type of action result: a JsonResult. It’s in JSON format, which is a lightweight data-interchange format (see http://json.org).

Task 3: add jquery to populate members combo box

Now we have to consume the JSON data and populate the combo box with members.

First we need references to the jquery javascript libraries, so open up the Site.Master and add the needed references:

<head runat="server">
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server" />
</title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jQuery-1.3.2.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
</head>

Open the Index2 view. To retrieve the list of members when the DOM of the page is loaded and to populate the combo box with these members, we can write the following  jquery:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
runat="server">
<script type="text/javascript">
$(document).ready(function()
{
// if the DOM is loaded, start retrieving the members
$.getJSON("/Members/GetMembers", null, function(data)
{
addMembers(data);
})
});
function addMembers(data)
{
// Get the DOM reference to the drop-down list.
var membersDropDownList = $("#MembersDropDownList");
// Loop through each member and populate the combo box.
$.each(data, function(index, optionData) {
membersDropDownList.append("<option value='"
+ optionData.ID
+ "'>" + optionData. LastName
+ "</option>");
});
};
</script>
<h2>Index2</h2>
<select id="MembersDropDownList" />
</asp:Content>

Take your time to study and understand the jquery syntax.

Now start the application and go to the page “/members/index2”. If everything works, the combo box should be populated:

Index2

Task 4: show member details

Finally, we want to show the details of the selected member. The first step to do that is to provide a new action member for the MemberController that retrieves the details of a member. So add the following action method to the MemberController:

public JsonResult GetMemberDetails(int memberID)
{
// Get member details using model
Member m = MemberService.GetMember(memberID);
// Return list of members as JSON
return this.Json(m);
}

The next thing is to make sure that when the selected combo box item changes, the member details are updated. Again, we will do that with jquery:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
runat="server">
<script type="text/javascript">
$(document).ready(function()
{
$.getJSON("/Members/GetMembers", null, function(data)
{
addMembers(data);
})
var membersDropDownList = $("#MembersDropDownList");
membersDropDownList.change(function() {
populateDetails(this.value);
})
});
function populateDetails(id)
{
$.getJSON("/Members/GetMemberDetails",
{memberID : id }, function(data) {
$("#FirstName").html(data.FirstName);
$("#LastName").html(data.LastName);
});
}
function addMembers(data)
{
// Get the DOM reference to the drop-down list.
var membersDropDownList = $("#MembersDropDownList");
// Loop through each member and populate the combo box.
$.each(data, function(index, optionData) {
membersDropDownList.append("<option value='"
+ optionData.ID
+ "'>" + optionData.LastName
+ "</option>");
});
};
</script>
<h2>Index2</h2>
<select id="MembersDropDownList"></select>
<p />
<div>First name: <span id="FirstName"></span></div>
<div>Last name: <span id="LastName"></span></div>
</asp:Content>

Start the application again, go to the page “/members/index2” and select another member. The details should become visible:
 

Index2

One thing left: when we initially load this page, the member details are not filled in. To solve that, just add the following line of code:

<script type="text/javascript">
$(document).ready(function()
{
$.getJSON("/Members/GetMembers", null, function(data)
{
addMembers(data);
populateDetails(membersDropDownList.val());
})
var membersDropDownList = $("#MembersDropDownList");
membersDropDownList.change(function() {
populateDetails(this.value);
})
});
</script>

If you try it now, the member details will be visible when the page is first loaded.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.