O'Reilly logo

ASP.NET 4 24-Hour Trainer by Toi B. Wright

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13B. Partial Views in MVC

Partial views are reusable views that are both easy to create and use. Whenever you need to use the same markup in two different places, it is time to consider using a partial view. In this lesson I will show you how to create and use a partial view.

CREATING A PARTIAL VIEW

The first step when creating a partial view is to create the model for the view. I use the following model in this lesson:

namespace Lesson13b.Models
{
    public class Address
    {
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
    }
}

Partial views are usually stored in the Shared subfolder of the Views folder. To create a new partial view right-click the Shared folder and select View from the Add menu to open the Add View dialog box (see Figure 13B-1). Make sure to click the Create a partial view (.ascx) checkbox before you click the Add button.

The Add View dialog box creates a file with an ASCX file extension. These are the contents of the Address.ascx file that has been created by the Add View dialog box:

<%@ Control Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<Lesson13b.Models.Address>" %>

    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
<legend>Fields</legend> <div class="editor-label"> <%: Html.LabelFor(model => model.Address1) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Address1) %> <%: Html.ValidationMessageFor(model ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required