ASP.NET MVC QuickStart 2: Implement model, controller and view

…continued from part 1.

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:

Add member

Keep it simple, and define the following properties:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public class Member
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}

The model is also responsible for data access operations, so add another class to the Model folder and call it MemberService.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
/// <summary>
/// For simplicity, MemberService mimics a member service providing
/// basic member operations and working with mock data.
/// </summary>
public class MemberService
{
private static List<Member> members;
static MemberService()
{
// Create some dummy members
members = new List<Member>();
members.Add(new Member()
{ ID = 0, FirstName = "Geoffrey", LastName = "Denver" });
members.Add(new Member()
{ ID = 1, FirstName = "Todd", LastName = "Lorn" });
members.Add(new Member()
{ ID = 2, FirstName = "Loren", LastName = "Lyle" });
members.Add(new Member()
{ ID = 3, FirstName = "Ralphie", LastName = "Ethan" });
members.Add(new Member()
{ ID = 4, FirstName = "Mervyn", LastName = "Tyler" });
}
public static List<Member> GetMembers()
{
return members;
}
}
}

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:

Add controller

Click Add. The new file membersController.cs will now be added to the Controllers folder. Modify it as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class MembersController : Controller
{
//
// GET: /Members/
public ActionResult Index()
{
// Get a list of members using the model
List<Member> members = MemberService.GetMembers();

// return this list to the default view
return View(members);
}
}
}

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:

Debugging not enabled

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:

Web page

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:
 

MembersController

Hit F5 again, and then you’ll see the following error appear:
 

Server error

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:

Add view

Then select Add View and fill in the required fields as follows:

Add view

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:

<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<
MvcApplication1.Models.Member>>"
%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
runat="server">
<h2>Index</h2>
<table>
<tr>
<th></th>
<th>
ID
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
</tr>
<% foreach (var item in Model) { %>

<tr>
<td>
<%= Html.ActionLink("Edit", "Edit", new {
/* id=item.PrimaryKey */ }) %> |
<%= Html.ActionLink("Details", "Details", new {
/* id=item.PrimaryKey */ })%>
</td>
<td>
<%= Html.Encode(item.ID) %>
</td>
<td>
<%= Html.Encode(item.FirstName) %>
</td>
<td>
<%= Html.Encode(item.LastName) %>
</td>
</tr>

<% } %>
</table>
<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>
</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:

<%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %> |
<%= 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:

My MVC application

Note: none of the generated links work at this point, so that’s what we’ll do next.
 
Go to part 3.
Advertisements

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