Objectives
In this Hands-On Lab, you will create functionality to display a list of members. In particular, you will:
- Create a model
- Create a controller
- Create a view
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 1 code.
Task 1: create a model
In ASP.NET MVC, the model is responsible for providing the needed data and applying the business logic. Therefore, we will start by creating the model for our web application. We will first create a Member business entity, so right click the Model folder, select Add -> Class and call the new class Member.cs:
Keep it simple, and define the following properties:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: namespace MvcApplication1.Models
6: {
7: public class Member
8: {
9: public int ID { get; set; }
10: public string FirstName { get; set; }
11: public string LastName { get; set; }
12: }
13: }
The model is also responsible for data access operations, so add another class to the Model folder and call it MemberService.cs:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: namespace MvcApplication1.Models
6: {
7: /// <summary>
8: /// For simplicity, MemberService mimics a member service providing
9: /// basic member operations and working with mock data.
10: /// </summary>
11: public class MemberService
12: {
13: private static List<Member> members;
14: static MemberService()
15: {
16: // Create some dummy members
17: members = new List<Member>();
18: members.Add(new Member()
19: { ID = 0, FirstName = "Geoffrey", LastName = "Denver" });
20: members.Add(new Member()
21: { ID = 1, FirstName = "Todd", LastName = "Lorn" });
22: members.Add(new Member()
23: { ID = 2, FirstName = "Loren", LastName = "Lyle" });
24: members.Add(new Member()
25: { ID = 3, FirstName = "Ralphie", LastName = "Ethan" });
26: members.Add(new Member()
27: { ID = 4, FirstName = "Mervyn", LastName = "Tyler" });
28: }
29: public static List<Member> GetMembers()
30: {
31: return members;
32: }
33: }
34: }
At this point, we have created a very basic model that we can use to retrieve members.
Task 2: create a controller
The next step is to create a controller that will be responsible for retrieving the member data and passing this data to a view. To do that, right click the Controllers folder, select Add -> Controller and call it MembersController:
Click Add. The new file membersController.cs will now be added to the Controllers folder. Modify it as follows:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.Mvc;
6: using System.Web.Mvc.Ajax;
7: using MvcApplication1.Models;
8: namespace MvcApplication1.Controllers
9: {
10: public class MembersController : Controller
11: {
12: //
13: // GET: /Members/
14: public ActionResult Index()
15: {
16: // Get a list of members using the model
17: List<Member> members = MemberService.GetMembers();
18:
19: // return this list to the default view
20: return View(members);
21: }
22: }
23: }
Put a breakpoint on the first line of the Index method and hit F5 to debug the web application. The first time you will see the following dialog:
Just click OK because we want to enable debugging, and the web page will appear. Then, modify the URL to trigger the Index action of the MembersController we just created, as follows:
When you do this, the routing system will map this URL to the Index action method of the Members controller, and so the Index method will execute:
Hit F5 again, and then you’ll see the following error appear:
This is normal, because the Index action method tries to find the default view Index.aspx in the Views/Members folder, but we didn’t create that view yet.
Task 3: create a view
In this task, we will create a view to display a list of members. To do that, open MembersController.cs and right click the Index method:
Then select Add View and fill in the required fields as follows:
Make sure that:
- The View name is called Index.
- You check the Create a strongly typed view check box, and set the View data class to MvcApplication1.Models.Member. This way, we will be able to access the member data in the view in a strongly typed way.
- Select List as the View content. This will generate code that displays a list of members.
Click Add. The view Index.aspx will be generated and added to the Views/Members folder of the project:
1: <%@ Page Title="" Language="C#"
2: MasterPageFile="~/Views/Shared/Site.Master"
3: Inherits="System.Web.Mvc.ViewPage<IEnumerable<
4: MvcApplication1.Models.Member>>" %>
5: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
6: runat="server">
7: Index
8: </asp:Content>
9: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
10: runat="server">
11: <h2>Index</h2>
12: <table>
13: <tr>
14: <th></th>
15: <th>
16: ID
17: </th>
18: <th>
19: FirstName
20: </th>
21: <th>
22: LastName
23: </th>
24: </tr>
25: <% foreach (var item in Model) { %>
26:
27: <tr>
28: <td>
29: <%= Html.ActionLink("Edit", "Edit", new {
30: /* id=item.PrimaryKey */ }) %> |
31: <%= Html.ActionLink("Details", "Details", new {
32: /* id=item.PrimaryKey */ })%>
33: </td>
34: <td>
35: <%= Html.Encode(item.ID) %>
36: </td>
37: <td>
38: <%= Html.Encode(item.FirstName) %>
39: </td>
40: <td>
41: <%= Html.Encode(item.LastName) %>
42: </td>
43: </tr>
44:
45: <% } %>
46: </table>
47: <p>
48: <%= Html.ActionLink("Create New", "Create") %>
49: </p>
50: </asp:Content>
The view already contains HTML to display the list of members, and the code is very straightforward. Notice:
- the foreach statement that is used to loop all elements of the Model property. Because we made it a strongly typed view, it inherits from ViewPage<IEnumerable<MvcApplication1.Models.Member>>, and therefore the Model property if of type IEnumerable<MvcApplication1.Models.Member> and thus we can use it in a strongly typed way.
- The use of Html.ActionLink helper method to generate edit, create and details links. So you don’t have to write links yourself, instead always let ASP.NET MVC generate these for you (it will use routing mechanism to do so).
- The use of Html.Encode helper method, which encodes HTML to avoid cross-site scripting.
One more thing to do manually: replace the documented code in the action links so that we assign the primary key to each member instance for the Edit and Details links:
1: <%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %> |
2: <%= Html.ActionLink("Details", "Details", new { id=item.ID })%>
Run the web application again, change the url to http://localhost:3382/members/index and the list of members will be shown:
Note: none of the generated links work at this point, so that’s what we’ll do next.