How To: Use ASP.NET MVC

J.D. Meier, Alex Homer, David Hill, Jason Taylor, Prashant Bansode, Lonnie Wall, Rob Boucher Jr, Akshay Bogawat.

Applies To

  • ASP.NET 3.5
  • Visual Studio 2008
  • ASP.NET MVC Framework

Summary

This How To article shows you how to create a Model View Controller (MVC) application using the ASP.NET MVC Framework. It shows you how to use Visual Studio to create the initial template application containing the required folders and files, and then add controllers and views to the application.

Contents

  • Objectives
  • Overview
  • Before you Begin
  • Summary of Steps
  • Step 1 - Create a Solution for an ASP.NET MVC Application using Visual Studio 2008
  • Step 2 – Add a Controller to the Application
  • Step 3 – Add a View to the Application
  • Step 4 – Add an Action to the Controller
  • Step 5 – Add Content to the View
  • Step 6 – Add Logic Code to the View
  • Additional Resources

Objectives

  • Learn how to create an ASP.NET MVC application solution
  • Learn how to add controller classes to the application
  • Learn how to add View classes to the application
  • Learn how to use logic code, actions, and parameters within controller class
  • Learn how to use logic code and view data within the view class

Overview

Use Visual Studio 2008 to create an ASP.NET MVC Web project containing the solution files, folders, and initial content for an MVC Web application implementation. Add your own controller and view classes to the application, and write code to implement the actions, handle parameters, and populate views.

Before you Begin

Download and install the Microsoft MVC Framework from the Microsoft Download Web site at http://www.asp.net/MVC/. This installs the features and templates required for creating ASP.NET MVC applications into Visual Studio.

Summary of Steps

  • Step 1 - Create a Solution for an ASP.NET MVC Application using Visual Studio 2008
  • Step 2 – Add a Controller to the Application
  • Step 3 – Add a View to the Application
  • Step 4 – Add an Action to the Controller
  • Step 5 – Add Content to the View
  • Step 6 – Add Logic Code to the View

Step 1 – Create a Solution for an ASP.NET MVC Application using Visual Studio 2008

This step shows you how to create a new solution for an ASP.NET MVC Web application.
  1. Open the File menu, point to New, and then click Project….
  2. In the list of project types in the New Project dialog box, expand the language of your choice and select Web. In the Templates list, select ASP.NET MVC Web Application.
  3. Type a name for the new project in the Name text box, select a location, and then click OK.
  4. In the Create Unit Test dialog box, select “Yes, create a unit test project” and then click OK.
  5. Press F5 to run the solution, and click OK in the dialog that asks if you want to modify the Web.config file for debugging. You will see an outline MVC application implementation with a “Home” page and an “About” page based on a single master page.

This step creates a solution containing two projects. The first contains a master page for the site (in the Views\Shared subfolder), a controller for the Home and Account pages (in the Controllers subfolder), and the Home and About views (in the Views subfolder). It also contains a Global.asax file that initializes the default routing table, a style sheet (in the Content subfolder), a web.config file, and a Default.aspx page that ensures that requests for the default site URL go through IIS.

The second (test) project contains a test for controller in the application project. The tests verify that that the two methods of the Home and About pages controller instantiate the correct views.

Step 2 – Add a Controller to the Application

This step shows you how to add a new controller to the application. This controller will display a page containing information about customers.
  1. In Solution Explorer, right-click the Controllers folder, click Add, and then click New Item.
  2. In the Categories list, click Web. In the Templates list, click MVC Controller Class.
  3. Change the name for the new controller to CustomerController and click Add.

This step adds a new controller class implementation to the project (the ASP.NET MVC Framework requires the name to end with “Controller”), and displays it in the Visual Studio editor. The new class inherits the Controller base class, and contains a default method named Index where you enter code to execute when a user request loads this controller.

Step 3 – Add a View to the Application

This step shows you how to add a new view to the application. This view will display a list of customers.
  1. In Solution Explorer, right-click the Views folder, click Add, and then click New Folder.
  2. Change the name of the folder to Customer (views for a controller must reside in a subfolder of the Views folder that has the same name as the corresponding controller).
  3. In Solution Explorer, right-click the Customer folder, click Add, and then click New Item.
  4. In the Categories list, click Web. In the Templates list, click MVC View Content Page. This ensures that the new view uses the site master page. If you do not want the new view to use the site master page, click MVC View Page instead.
  5. Change the name for the new view to CustomerView and click Add.
  6. If you selected MVC View Content Page, specify the master page to use for the new view. Expand the list of Project Folders and then expand the Views folder, then click the Shared folder. In the Contents of folder pane, click Site.master and then click OK.

This step adds the new view to the application and displays it in the Visual Studio editor. It is empty, ready for you to add the content to display to the user.

Step 4 – Add an Action to the Controller

This step shows you how to add an action to a controller. An action is a public method that users can execute by appending the name of the controller and the name of the method to the Web site’s URL. The code in the action method will set any required properties of the appropriate view (it can dynamically select which view to use) and then display that view. Additional parameters passed to the controller in the URL appear as parameters of the action method.
  1. In Solution Explorer, double-click the file CustomerController.cs or CustomerController.vb (in the Controllers subfolder) to open it in the editor.
  2. Replace the default Index method with the following code that implements an action named GetList, and which takes a string parameter named id:
C#
public ActionResult GetList(String id)
{
  // If the user specified a value after the action name in the request
  // URL, it will appear as the id parameter of the action method. 
  if (null != id && id.Length > 0)
  {
    ViewData["QueryText"] = id;
  }
  else
  {
    ViewData["QueryText"] = "%";
  }
  return View("CustomerView"); 
}

Visual Basic
Public Function GetList(String id) As ActionResult
{
  ' If the user specified a value after the action name in the request
  ' URL, it will appear as the id parameter of the action method. 
  If (Not id Is Nothing) And (id.Length > 0) Then
    ViewData("QueryText") = id
  Else
    ViewData("QueryText") = "%"
  End If
  Return View("CustomerView") 
End Function

The code in the method first checks if the id parameter contains a value. If it does, it passes this to the view as the QueryText property value using the ViewData method. If the id parameter does not contain a value, it passes the string "%" as the QueryText property value. Finally, it instantiates and displays the view named CustomerView.

Step 5 – Add Content to the View

This step shows you how to add content to a view. The view can contain code that uses the values of properties passed to it by the controller. This example uses the QueryText property value passed from the CustomerController to select one or more customers and display them in a GridView control.
  1. In Solution Explorer, double-click the file CustomerView.aspx (in the Views\Customer subfolder) to open it in the editor.
  2. Click the Design tab at the bottom of the editor window to switch to design view.
  3. Drag a GridView control from the Data tab of the toolbox onto the view. If you are using a master page, you must drop it inside the ContentControl in the view.
  4. In the GridView Tasks menu, click Auto Format, select Slate in the Select a scheme list, and then click OK (if you cannot see the GridView Tasks menu, click on the GridView control to select it and then click on the arrow indicator that appears at the top right).
  5. Open the GridView Tasks menu again and select <New data source…> in the Choose Data Source drop-down list.
  6. In the Data Source Configuration wizard, select Database in the “Where will the application get data from” list and then click OK.
  7. In the Choose Your Data Connection step of the Wizard, click New Connection to open the Choose Data Source dialog. Select SQL Server and click Continue.
  8. In the Add Connection dialog, type .\SQLExpress in the Server name text box and open the “Select or enter a database name” drop-down list. Select a database from the list (use the AdventureWorks database if it is available) and then click OK. The database must contain a table that has a column of type varchar or nvarchar (a string value).
  9. In the Data Source Configuration wizard, click Next twice to get to the Configure the Select Statement step.
  10. Select a table in the database that has a column of type varchar or nvarchar (a string value), set the check box marked with an asterisk (), and then click Next*.
  11. Click Test Query to ensure that you have a valid connection and query statement, then click Finish.
  12. To display the view, you can easily add a link to the "Home" page of the default ASP.NET MVC application. In Solution Explorer, double-click the file Site.master (in the Shared subfolder) to open it in the editor.
  13. Scroll down to find the two Html.ActionLink controls that provide the links to the "Home" and "About" pages. Insert a new <li> element and, inside it, a new Html.ActionLink control that specifies the text of the link, the action name, and the controller name; as shown in the following code:
<li>
    <%= Html.ActionLink("Customers", "GetList", "Customer")%>
</li>
  1. Press F5 to save, compile, and run the application.
  2. Click the new Customers link in the default page to open the list of customers (or the contents of whichever database table you selected in this step).

This step populates the view with all of the rows in the table you selected. The GridView and SqlDataSource controls extract the data from the database after the view loads, and populate the view before it is displayed to the user. However, the action method GetList can also accept a parameter defined by adding a value to the end of the request URL. To see this, you must carry out the following step to add logic code to the view.

Step 6 – Add Logic Code to the View

This step shows you how to add code to a view that can manipulate the contents of the view. In this example, the code uses the QueryText property value passed from the CustomerController to add a SELECT parameter to the data source that populates the GridView control.
  1. In Solution Explorer, double-click the file CustomerView.aspx (in the Views\Customer subfolder) to open it in the editor.
  2. Click the Source tab at the bottom of the editor window to switch to source view so that you can see the ASPX code.
  3. Add the following HTML heading element immediately above the GridView control:
<h2>Customers matching the query: <%= ViewData["QueryText"]%></h2> 
  1. Find the line that contains the SQL statement generated by the Wizard when you placed the GridView control on the page. The SQL statement is the value of the SelectCommand element located within the SqlDataSource element.
  2. Add a suitable WHERE clause to the end of the SQL statement so that it specifies a value for one of the string-type (varchar or nvarchar) columns in the table you selected. For example, WHERE (CustomerName LIKE @CustomerName)
  3. In Solution Explorer, double-click the file CustomerView.cs or CustomerView.vb (in the Views\Customer subfolder) to open it in the editor.
  4. Add a Page_Load event handler to the class, as shown in the following code:
public void Page_Load()
{
}
  1. Write code within the Page_Load event handler that creates a parameter with the appropriate name (the name you specified in the WHERE clause) and adds this to the SelectParameters collection in the SqlDataSource control; as shown in the following code:
SqlDataSource1.SelectParameters.Add("CustomerName", Server.UrlDecode(ViewData["QueryText"].ToString()));
  1. Press F5 to save, compile, and run the application.
  2. Click the new Customers link in the default page to open the list of all customers (or the contents of whichever database table you selected in this step).
  3. In the Address box of your browser, add a foreword slash and the name of a customer (or the value from the string column of one row of whichever database table you selected in this step). For example, your URL cold be like the following:
http://localhost:50629/Customer/GetList/John%20Smith
  1. Press Return to load this page. You will see only the row(s) containing this value for the column to which the parameter applies. In addition, the heading in the view now displays the query text.

In this step, you took advantage of the way that the ASP.NET MVC Framework routes requests to the appropriate controller and action, and maps additional parts of the URL to parameters of the action method. This example uses the default id parameter, but you can use named parameters. For example, ASP.NET will map the query string: “FirstName=John&LastName=Smith” to two ViewData properties named FirstName and LastName.

You can also see how you can use render blocks to insert the values of the ViewData properties directly into the page. This is the approach used in this step to show the query text in the HTML heading element.

When populating parameters, it is a good idea to use the UrlDecode method (as demonstrated) to ensure that any spaces or other non-standard characters are correctly decoded from the URL.

Additional Resources

Last edited Dec 17, 2008 at 10:11 PM by prashantbansode, version 1

Comments

No comments yet.