Partager via


Walkthrough: Using MVC View Templates with Data Scaffolding

When you create an ASP.NET MVC application in Visual Studio, you have the option to create controllers and views that support data scaffolding. This walkthrough shows how to create a simple MVC application that takes advantage of the data templates for controllers and views that Visual Studio supports for MVC.

In this walkthrough, you will add a controller that already contains action methods for displaying, editing, and updating model data. By using the data scaffolding that is built into ASP.NET MVC, you will also generate views that are based on the model that you define.

A Visual Studio project with source code is available to accompany this topic: Download.

Prerequisites

In order to complete this walkthrough, you will need:

  • Microsoft Visual Studio 2008 SP1 or later. You cannot use Microsoft Visual Web Developer Express for this walkthrough.

  • The ASP.NET MVC 2 framework. If you have installed Visual Studio 2010, the ASP.NET MVC 2 is already installed on your computer. To download the most up-to-date version of the framework, see the ASP.NET MVC download page.

Creating a New MVC Project

To begin, you will create a new ASP.NET MVC project. To keep this walkthrough simple, you will not create the test project that is an option for ASP.NET MVC projects. For more information about how to create an MVC project, see Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio.

To create a new MVC project

  1. On the File menu, click New Project.

  2. In the New Project dialog box under Project types, expand Visual Basic or Visual C#, and then click Web.

  3. Under Visual Studio installed templates, select ASP.NET MVC 2 Web Application.

  4. In the Name box, type MvcDataViews.

  5. In the Location box, enter the name of the project folder.

  6. Select Create directory for solution.

  7. Click OK.

  8. In the Create Test Project dialog box, select No, do not create a unit test project.

    Note

    If you are using Visual Studio 2008 Standard, the Create Unit Test Project dialog box is not displayed. Instead, the new MVC application project is created without a test project.

  9. Click OK.

    The new MVC application project is created.

Creating a Model Class

This walkthrough uses a simple data model whose values will be added, edited, and displayed by using the views templates. You will create a class that defines a person. For this walkthrough, a person class has properties for ID, name, and age.

To create a model class

  1. In Solution Explorer, right-click the Models folder, click Add, and then click Class.

  2. Change the name of the class to Person.vb or Person.cs.

  3. Add the following code for the Person class:

    Imports System.Web.DynamicData
    Imports System.ComponentModel.DataAnnotations
    
    Public Class Person
        <Required(ErrorMessage:="The ID is required.")> _
        Private _Id As Integer
        Public Property Id() As Integer
            Get
                Return _Id
            End Get
            Set(ByVal value As Integer)
                _Id = value
            End Set
        End Property
    
        <Required(ErrorMessage:="The name is required.")> _
        Private _Name As String
        Public Property Name() As String
            Get
                Return _Name
            End Get
            Set(ByVal value As String)
                _Name = value
            End Set
        End Property
    
        <Range(1, 200, ErrorMessage:="A number between 1 and 200.")> _
        Private _Age As Integer
        Public Property Age() As Integer
            Get
                Return _Age
            End Get
            Set(ByVal value As Integer)
                _Age = value
            End Set
        End Property
    
        <RegularExpression("((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", _
                ErrorMessage:="Invalid phone number.")> _
        Private _Phone As String
        Public Property Phone() As String
            Get
                Return _Phone
            End Get
            Set(ByVal value As String)
                _Phone = value
            End Set
        End Property
    
        <RegularExpression("^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", _
                ErrorMessage:="Invalid email address.")> _
        Private _Email As String
        Public Property Email() As String
            Get
                Return _Email
            End Get
            Set(ByVal value As String)
                _Email = value
            End Set
        End Property
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    
    namespace MvcDataViews.Models
    {
        public class Person
        {
            [Required(ErrorMessage = "The ID is required.")]
            public int Id { get; set; }
    
            [Required(ErrorMessage = "The name is required.")]
            public string Name { get; set; }
    
            [Range(1, 200, ErrorMessage = "A number between 1 and 200.")]
            public int Age { get; set; }
    
            [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", 
                ErrorMessage = "Invalid phone number.")]
            public string Phone { get; set; }
    
            [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", 
                ErrorMessage = "Invalid email address.")]
            public string Email { get; set; }
        }
    }
    
  4. In the Build menu, click Build MvcDataViews to build the project and to create an instance of the Person object.

    Note

    This step is necessary is because Visual Studio uses the model instance when it generates the controller code and view markup based on MVC templates.

  5. Save and close the file.

Adding a Controller

Next, you will create a controller that contains action-method stubs that will render views to create, update, and display a list of Person objects.

To add the data-handling controller

  1. In Solution Explorer, right-click the Controllers folder, click Add, and then click Controller.

  2. Name the controller PersonController.

  3. Select the Add action methods for Create, Update, and Details scenarios check box.

  4. Click Add.

    The new controller is added to the application. The controller contains the following action methods: Index, Details, Create (for HTTP GET), Create (for HTTP POST), Delete (for HTTP GET), and Delete (for HTTP POST), Edit (for HTTP GET) and Edit (for HTTP POST).

  5. At the top of the PersonController class, add the following line of code:

    Shared people As New List(Of Person)()
    
    static List<Person> people = new List<Person>();
    

    This code creates a list of Person objects.

  6. Save the file.

Adding the List View

You can now add the data views. The first view you create is a list view that is rendered by the Index action method. This view displays the Person objects that you create in a grid. Each row also includes links for displaying the person in a details view or an edit view.

To add the list view

  1. Open or switch to the PersonController class in the editor and locate the Index action method.

  2. Right-click inside the Index action method, and then click Add View.

  3. In the View name box, enter Index.

  4. Select the Create a strongly-typed view check box.

  5. In the View data class list, select MvcDataViews.Models.Person.

  6. In the View content list, select List.

    Note

    Leave the Select master page check box selected.

  7. Click Add.

    A view named Index is created inside a new Person folder. The Index view will contain the MVC template for displaying a data list.

  8. In the Index view, locate the Html.ActionLink controls and change them as shown in the following example:

    <%=Html.ActionLink("Edit", "Edit", New With {.id = item.Id})%> |
    <%=Html.ActionLink("Details", "Details", item)%> |
    <%=Html.ActionLink("Delete", "Delete", New With {.id = item.Id})%>
    
    <%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |
    <%= Html.ActionLink("Details", "Details", item )%> |
    <%= Html.ActionLink("Delete", "Delete", new { id=item.Id })%>
    
  9. In PersonController, replace the Index action method with the following code:

    Function Index() As ActionResult
        Return View(people)
    End Function
    
    public ActionResult Index()
    {
        return View(people);
    }
    
  10. Save the files.

Adding the Create View

Next, you will add a view for creating Person objects. When you create a Person object, you define the name, age, and ID of the person. The PersonController has two Create action methods. One Create action method receives an HTTP GET request and renders the create view. The other Create action method receives the HTTP POST request from the create view, checks the validity of the data, adds data to the list, and redirects to the Index action method.

To add the create view

  1. Open or switch to PersonController in the editor and locate the Create action method that handles HTTP GET.

  2. Right-click inside the Create action method, and then click Add View.

  3. In the View name box, enter Create.

  4. Select the Create a strongly-typed view check box.

  5. In the View data class list, select MvcDataViews.Models.Person.

  6. In the View content list, select Create.

    Note

    Leave the Select master page check box selected.

  7. Click Add.

    A view named Create is added to the project.

  8. In PersonController, replace the Create action method that handles HTTP POST with the following code:

    <HttpPost()> _
    Function Create(ByVal p As Person) As ActionResult
        If Not ModelState.IsValid Then
            Return View("Create", p)
        End If
    
        people.Add(p)
    
        Return RedirectToAction("Index")
    End Function
    
    [HttpPost]
    public ActionResult Create(Person p)
    {                      
        if (!ModelState.IsValid)
        {
            return View("Create", p);
        }
    
        people.Add(p);
    
        return RedirectToAction("Index");
    }
    
  9. Save the files.

Adding the Details View

The details view displays the values for a single Person object. The view also provides links to an edit view and for returning to the list view.

To add the details view

  1. Open or switch to PersonController in the editor and locate the Details action method.

  2. Right-click inside the Details action method and then click Add View.

  3. In the View name box, enter Details.

  4. Select the Create a strongly-typed view check box.

  5. In the View data class list, select MvcDataViews.Models.Person.

  6. In the View content list, select Details.

    Note

    Leave the Select master page check box selected.

  7. Click Add.

    A view named Details is added to the project.

  8. In the Details view, locate the Html.ActionLink control that links to the Edit view and change it as shown in the following example:

    <%= Html.ActionLink("Edit", "Edit", New With {.id = Model.Id})%> |
    <%= Html.ActionLink("Back to List", "Index") %>
    
    <%= Html.ActionLink("Edit", "Edit", new { id=Model.Id }) %> |
    <%= Html.ActionLink("Back to List", "Index") %>
    
  9. In PersonController, replace the Details action method with the following code:

    Function Details(ByVal p As Person) As ActionResult
        Return View(p)
    End Function
    
    public ActionResult Details(Person p)
    {
        return View(p);
    }
    
  10. Save the files.

Adding the Delete View

The delete view enables the user to remove a Person object from the list. The user has the option of either deleting the selected Person object or returning to the list view. The PersonController has two Delete action methods. One Delete action method receives an HTTP GET request and renders the delete view. The other Delete action method receives the HTTP POST request from the delete view, removes the selected object, and redirects to the Index action method.

To add the details view

  1. Open or switch to PersonController in the editor and locate the Details action method.

  2. Right-click inside the Delete action method and then click Add View.

  3. In the View name box, enter Delete.

  4. Select the Create a strongly-typed view check box.

  5. In the View data class list, select MvcDataViews.Models.Person.

  6. In the View content list, select Details.

    Note

    Leave the Select master page check box selected.

  7. Click Add.

    A view named Delete is added to the project.

  8. In PersonController, replace the Delete action method that handles HTTP GET with the following code:

    Function Delete(ByVal id As Integer) As ActionResult
        Dim p As New Person()
        For Each pn As Person In people
            If pn.Id = id Then
                p.Name = pn.Name
                p.Age = pn.Age
                p.Id = pn.Id
                p.Phone = pn.Phone
                p.Email = pn.Email
            End If
        Next
    
        Return View(p)
    End Function
    
    public ActionResult Delete(int id)
    {
        Person p = new Person();
        foreach (Person pn in people)
        {
            if (pn.Id == id)
            {
                p.Name = pn.Name;
                p.Age = pn.Age;
                p.Id = pn.Id;
                p.Phone = pn.Phone;
                p.Email = pn.Email;
            }
        }
    
        return View(p);
    }
    
  9. Replace the Delete action method that handles HTTP POST with the following code:

    <HttpPost()> _
    Function Delete(ByVal p As Person) As ActionResult
        For Each pn As Person In people
            If (pn.Id = p.Id) Then
                people.Remove(pn)
                Exit For
            End If
        Next
    
        Return RedirectToAction("Index")
    End Function
    
  10. Save the files.

Adding the Edit View

The edit view enables the user to change the values for one of the Person objects. The PersonController has two Edit action methods. One Edit action method receives an HTTP GET request and renders the edit view. The other Edit action method receives the HTTP POST request from the edit view, checks the validity of the data, updates data in the appropriate Person object, and redirects to the Index action method.

To add the edit view

  1. Open or switch to PersonController in the editor and locate the Edit action method that handles HTTP GET.

  2. Replace the Edit action method with the following code:

    Function Edit(ByVal id As Integer) As ActionResult
        Dim p As New Person()
        For Each pn As Person In people
            If pn.Id = id Then
                p.Name = pn.Name
                p.Age = pn.Age
                p.Id = pn.Id
                p.Phone = pn.Phone
                p.Email = pn.Email
            End If
        Next
    
        Return View(p)
    End Function
    
    public ActionResult Edit(int id)
    {
        Person p = new Person();
        foreach (Person pn in people)
        {
            if (pn.Id == id)
            {
                p.Name = pn.Name;
                p.Age = pn.Age;
                p.Id = pn.Id;
                p.Phone = pn.Phone;
                p.Email = pn.Email;
            }
        }
    
        return View(p);
    }
    
  3. Right-click inside the Edit action method, click Add View.

  4. In the View name box, enter Edit.

  5. Select the Create a strongly-typed view check box.

  6. In the View data class list, select MvcDataViews.Models.Person.

  7. In the View content list, select Edit.

  8. Leave the Select master page check box selected.

  9. Click Add.

    A view named Edit is added to the project.

  10. In PersonController, replace the Edit action method that handles HTTP POST with the following code:

    <HttpPost()> _
    Function Edit(ByVal p As Person) As ActionResult
        If Not ModelState.IsValid Then
            Return View("Edit", p)
        End If
    
        For Each pn As Person In people
            If pn.Id = p.Id Then
                pn.Name = p.Name
                pn.Age = p.Age
                pn.Id = p.Id
                pn.Phone = p.Phone
                pn.Email = p.Email
            End If
        Next
    
        Return RedirectToAction("Index")
    End Function
    
    [HttpPost]
    public ActionResult Edit(Person p)
    {
        if (!ModelState.IsValid)
        {
            return View("Edit", p);
        }
    
        foreach (Person pn in people)
        {
            if (pn.Id == p.Id)
            {
                pn.Name = p.Name;
                pn.Age = p.Age;
                pn.Id = p.Id;
                pn.Phone = p.Phone;
                pn.Email = p.Email;
            }
        }
    
        return RedirectToAction("Index");
    }
    
  11. Save and close the files.

Linking from the Home Page

To finish the application, you will add a link on the home page to the person list.

  1. In the Home folder, open the Index view.

  2. Add the following markup on the line after the </h2> tag:

    <p>
      <%=Html.ActionLink("Open Person List", "Index", "Person") %>
    </p>
    
  3. Save and close the file.

Testing the Application

You can now compile and run the application.

To test the application

  1. Type CTRL+F5 to start the application.

  2. On the home page, click Open Person List.

  3. Click Create New.

  4. Enter values in the Name, Age, Phone, Email, and Id boxes, and then click Create.

    The Index view is displayed and includes the person that you added to the list.

  5. Repeat the previous step several times to enter more people.

  6. In the Index view, click one of the Details links.

    The Details view is displayed.

  7. Click Back to List.

  8. Click one of the Edit links.

    The Edit view is displayed.

  9. Change the name or age of a person and then click Update.

    The Index view is displayed again with the data fields updated.

  10. Click one of the Delete links.

    The Delete view is displayed.

  11. Click the Delete button.

    The Index view is displayed once more with the selected entry removed.

Complete Example Code

The complete example code for this walkthrough is available as a Visual Studio project: Download.

See Also

Tasks

Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio

Concepts

Views and UI Rendering in ASP.NET MVC Applications

Other Resources

ASP.NET MVC 2