Export (0) Print
Expand All
1 out of 8 rated this helpful - Rate this topic

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 VMC, you will also generate views that are based on the model that you define.

In order to complete this walkthrough, you will need:

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

  • ASP.NET MVC 1.0.

You can download and install the ASP.NET MVC framework in the following ways:

  • Install the framework using the Microsoft Web Platform Installer. You can download the installer from the installation page on the Microsoft Web gallery site.

  • Download the framework from the ASP.NET MVC 1.0 page on the Microsoft Download Center.

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 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 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.

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:

  4. In the Build menu, click Build MvcDataViews to build the project and to create an instance of the Person object.

    Note 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.

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), Edit (for HTTP GET) and Edit (for HTTP POST).

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

            static List<Person> people = new List<Person>();
    
    

    This code creates a list of Person objects.

  6. Save the file.

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 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 { id = item.Id })%> |
    <%= Html.ActionLink("Details", "Details", new { id = item.Id })%>
    
    
    
  9. In PersonController, replace the Index action method with the following code:

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

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 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:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Person p)
    {
        if (!ModelState.IsValid)
        {
            return View("Create", p);
        }
    
        people.Add(p);
    
        return RedirectToAction("Index");
    }
    
    
    
  9. Save the files.

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 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 { id=Model.Id }) %> |
    
    
  9. In PersonController, replace the Details action method with the following code:

    
                                  public ActionResult Details(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;
            }
        }
    
        return View(p);
    }
    
    
    
  10. Save the files.

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:

    
                                  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;
            }
        }
    
        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:

    [AcceptVerbs(HttpVerbs.Post)]
    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;
            }
        }
    
        return RedirectToAction("Index");
    }
    
    
    
  11. Save and close the files.

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

To link 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:

    Can you tell us anything about this?
    
    
  3. Save and close the file.

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 Name, Age, and Id, 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.

The following example contains the completed code for this walkthrough. This includes only those files that are changed from the default MVC application.

The following example shows the Person model class:


                        public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}


The following example shows the PersonController class:


                        using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcDataViews.Models;

namespace MvcDataViews.Controllers
{
    public class PersonController : Controller
    {
        static List<Person> people = new List<Person>();
        //
        // GET: /Person/
        public ActionResult Index()
        {
            return View(people);
        }
        //
        // GET: /Person/Details/5
        public ActionResult Details(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;
                }
            }

            return View(p);
        }
        //
        // GET: /Person/Create
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Person/Create
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Person p)
        {
            if (!ModelState.IsValid)
            {
                return View("Create", p);
            }

            people.Add(p);

            return RedirectToAction("Index");
        }
        //
        // GET: /Person/Edit/5
        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;
                }
            }

            return View(p);
        }
        //
        // POST: /Person/Edit/5
        [AcceptVerbs(HttpVerbs.Post)]
        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;
                }
            }

            return RedirectToAction("Index");
        }
    }
}


The following example shows the Person\Index view:

<h2>Index</h2>

<p>
    <%=Html.ActionLink("Create New", "Create")%>
</p>

<table>
    <tr>
        <th></th>
        <th>
            Id
        </th>
        <th>
            Name
        </th>
    </tr>

<% For Each item In Model%>

    <tr>
        <td>
            <%=Html.ActionLink("Edit", "Edit", New With {.id = item.Id})%> |
            <%=Html.ActionLink("Details", "Details", New With {.id = item.Id})%>
        </td>
        <td>
            <%= Html.Encode(item.Id) %>
        </td>
        <td>
            <%= Html.Encode(item.Name) %>
        </td>
    </tr>

<% Next%>

</table>


The following example shows the Create view:

<h2>Create</h2>

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>

    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="Id">Id:</label>
            <%= Html.TextBox("Id") %>
            <%= Html.ValidationMessage("Id", "*") %>
        </p>
        <p>
            <label for="Name">Name:</label>
            <%= Html.TextBox("Name") %>
            <%= Html.ValidationMessage("Name", "*") %>
        </p>
        <p>
            <label for="Age">Age:</label>
            <%= Html.TextBox("Age") %>
            <%= Html.ValidationMessage("Age", "*") %>
        </p>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

<div>
    <%=Html.ActionLink("Back to List", "Index") %>
</div>


The following example shows the Details view:

<h2>Details</h2>

<fieldset>
    <legend>Fields</legend>
    <p>
        Id:
        <%= Html.Encode(Model.Id) %>
    </p>
    <p>
        Name:
        <%= Html.Encode(Model.Name) %>
    </p>
    <p>
        Age:
        <%= Html.Encode(Model.Age) %>
    </p>
</fieldset>
<p>
    <%=Html.ActionLink("Edit", "Edit", new { id=Model.Id }) %> |
    <%=Html.ActionLink("Back to List", "Index") %>
</p>


The following example shows the Edit view:

<h2>Edit</h2>

<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>

    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="Id">Id:</label>
            <%= Html.TextBox("Id", Model.Id) %>
            <%= Html.ValidationMessage("Id", "*") %>
        </p>
        <p>
            <label for="Name">Name:</label>
            <%= Html.TextBox("Name", Model.Name) %>
            <%= Html.ValidationMessage("Name", "*") %>
        </p>
        <p>
            <label for="Age">Age:</label>
            <%= Html.TextBox("Age", Model.Age) %>
            <%= Html.ValidationMessage("Age", "*") %>
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

<% } %>

<div>
    <%=Html.ActionLink("Back to List", "Index") %>
</div>


The following example shows the Home\Index view:

<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
    <%=Html.ActionLink("Open Person List", "Index", "Person") %>
</p>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>


Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft. All rights reserved.