Search Sreeni's Insights

Filter by content type
technical November 20, 2012 14 min read

How to build the views with layouts, partial views and HTML helpers? - Part 8

This article explains layouts, sections, partial views, child actions, display templates, built-in HTML helpers and custom helpers written with TagBuilder and the Razor helper.

Share:

How to build the views with layouts, partial views and HTML helpers? - Part 8

The views are the part of an MVC application which the users see, and they are also the part where the duplication grows faster than anywhere else. The same header is copied in every page, the same form is copied in the create and the edit screens, and the same if which colours the grade is repeated in three tables. When a designer asks for a small change, somebody must find all the copies. In the previous articles, we built the CRUD screens. In this article, we are going to see how Razor and the MVC give us the tools to avoid the duplication, the layouts and sections, the partial views, the child actions, the display templates, the built-in HTML helpers, our own HTML helpers written with TagBuilder and the Razor @helper.

Student Management System series:

  1. How to structure an ASP.NET MVC application? - Part 1
  2. How does an ASP.NET MVC request work from .NET 4.0 to 4.5? - Part 2
  3. How does routing work, with custom, nested and area routes? - Part 3
  4. How to model the data with Entity Framework and LINQ? - Part 4
  5. How lambda expressions, extension methods, delegates and events reduce the code? - Part 5
  6. How to build CRUD with Razor views and dependency injection? - Part 6
  7. How to remove the repeated code with a base controller, base service and base repository? - Part 7
  8. How to build the views with layouts, partial views and HTML helpers? - Part 8 (this article)
  9. How to use filters, model binding and validation? - Part 9
  10. How to add registration, login, forgot password, change password, profile and logout? - Part 10
  11. How to build a Web API with ASP.NET MVC 4? - Part 11
  12. How to test the application and keep it clean? - Part 12

TL;DR Summary

  • A layout is the master page, @RenderBody() shows the view and @RenderSection() gives the places for the page specific content.
  • Pass the data to a view in the strongly typed model first, ViewBag for the small extras and TempData for one redirect.
  • HTML helpers generate the HTML for us, and the ...For versions use a lambda expression so that the names are checked by the compiler.
  • A partial view is a reusable piece of markup, and a child action is a partial view which has its own controller action.
  • A display template or an editor template decides how a type is shown everywhere in the application.
  • A custom HTML helper is an extension method of HtmlHelper, and TagBuilder builds the tag with the safe encoding.
  • The Razor @helper is a small reusable function which is written with the markup, inside a view.

Common Challenges

The copy of the markup

A header, a form and a table row which are copied to many views are changed in many views. One of them is always forgotten.

The logic in the view

A view which has long if statements to decide the colour of a grade or the text of a button is hard to read and impossible to unit test.

The HTML in the controller

Some developers build the HTML string in the controller or in the model, to avoid the repetition. Now the controller knows the markup and the CSS classes, and the designer can’t change it without a developer.

Razor in short

Razor was introduced with ASP.NET MVC 3, and it is the default view engine of MVC 4. Find below the rules which cover most of what we write,

  • @ starts a piece of code. @Model.Email is an expression, and Razor finds the end of it by itself.
  • @{ ... } is a block of code, where we can declare the variables. @if, @foreach and @using start a statement with the braces and the markup inside.
  • The output of an expression is HTML encoded. @Html.Raw(value) is the only way to write the raw HTML, so use it with care.
  • @@ writes one @, and @: writes a line of text inside a code block.
  • @model declares the type of the model, and Model is the object of that type.

Layouts and sections

The layout is the master page. It has the header, the navigation and the footer, and the place where each view is rendered. Find below the layout of the sample,

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - Student Management System</title>
    <link href="~/Content/Site.css" rel="stylesheet" />
</head>
<body>
    <header>
        <div class="wrap">
            <h1>Student Management System</h1>
            <nav>
                @Html.ActionLink("Students", "Index", "Students", new { area = "" }, null)
                @Html.ActionLink("Departments", "Index", "Departments", new { area = "" }, null)
                @Html.ActionLink("Quick search", "QuickSearch", "Students", new { area = "" }, null)
                @Html.ActionLink("Announcements", "Index", "Announcements", new { area = "" }, null)
                @Html.ActionLink("Admin", "Index", "Dashboard", new { area = "Admin" }, null)
            </nav>
        </div>
    </header>
    <div class="wrap content">
        @RenderBody()
    </div>
    <footer>
        <div class="wrap">
            ASP.NET MVC 4, Entity Framework 5, .NET Framework 4.5
            @if (ViewBag.ActionMilliseconds != null)
            {
                <span class="timer">Action method took @ViewBag.ActionMilliseconds ms</span>
            }
        </div>
    </footer>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>

The ~/ at the start of a path is the application root, and Razor resolves it for us. The Views/_ViewStart.cshtml sets the layout for all the views, so we don’t repeat it,

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

A view which needs something in the page specific place, for example the validation scripts of a form, defines the section with the same name,

@section Scripts {
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}

The layout renders it at the end of the page, after the jQuery. The required: false means that a view without the section is fine. The ViewBag.Title which each view sets is used by the layout for the page title. The timer text in the footer is written by an action filter, and we will see it in Part 9.

Passing the data to a view

There are three ways to give the data to a view, and each has its place,

WayLifetimeUse
The model (@model)The current requestThe main data of the page. It is strongly typed, so the compiler and the IntelliSense help us
ViewBag or ViewDataThe current requestThe small extras like a page title or the paging values. It is not checked by the compiler, a mistyped name is found at the runtime
TempDataThe next request onlyThe message after a redirect, like “Student created”

The details screen of a student needs the student and also the list of the courses for the enroll dropdown. A model which carries both is better than the ViewBag,

public class StudentDetailsModel
{
    public Student Student { get; set; }
    public SelectList AvailableCourses { get; set; }
}

and the controller prepares it, with only the courses where the student is not enrolled yet,

private StudentDetailsModel BuildDetailsModel(Student student)
{
    var enrolled = student.Enrollments.Select(e => e.CourseId).ToList();
    var available = _catalog.Courses().Where(c => !enrolled.Contains(c.Id)).ToList();

    return new StudentDetailsModel
    {
        Student = student,
        AvailableCourses = new SelectList(available, "Id", "Title")
    };
}

The built-in HTML helpers

An HTML helper is a method which returns the HTML. The Html property of a view is an HtmlHelper, and the MVC gives us many methods on it,

HelperWhat it generates
Html.ActionLinkAn anchor with a URL from the routing
Html.BeginFormThe form tag, with the using block to close it
Html.TextBoxFor(m => m.Email)An input with the name, id and value from the model, and the validation attributes
Html.LabelFor, Html.ValidationMessageForThe label and the validation message of a property
Html.DropDownList, Html.DropDownListForA select from a SelectList
Html.DisplayFor, Html.EditorForThe value of a property with a display or editor template
Html.AntiForgeryTokenThe hidden field for the anti-forgery check
Html.Partial, Html.ActionA partial view, and the output of a child action
Html.RawThe text without the encoding

The helpers which end with For take a lambda expression, m => m.Email. The helper reads the property name, the type and the attributes from the expression, so that a rename of the property is a compile error and not a silent bug. The enroll form of the details screen uses a DropDownList,

<div class="enroll">
    @using (Html.BeginForm("Enroll", "Students", new { id = Model.Student.Id }, FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <label for="courseId">Enroll in a course</label>
        @Html.DropDownList("courseId", Model.AvailableCourses, "- select a course -")
        <input type="submit" value="Enroll" />
    }
</div>

The first parameter of DropDownList is the name of the field, so the posted value is bound to the courseId parameter of the Enroll action. The third parameter is the text of the empty option. The HTML which it produces is,

<form action="/Students/Enroll/1" method="post">
  <input name="__RequestVerificationToken" type="hidden" value="..." />
  <label for="courseId">Enroll in a course</label>
  <select id="courseId" name="courseId"><option value="">- select a course -</option> ... </select>

The screen, with a course selected, and after the enrollment,

The enroll form with a course selected
The enroll form with a course selected
The student after the enrollment
The student after the enrollment

The action which receives the form calls the Enroll of the service. The courseId is the nullable int?, because the user can post the form without selecting a course, and a non-nullable parameter would throw an exception for the missing value,

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Enroll(int id, int? courseId)
{
    return Execute(() =>
    {
        if (!courseId.HasValue)
            throw new BusinessRuleException("Select a course to enroll");

        _service.Enroll(id, courseId.Value);
        return Success("Student enrolled in the course", RedirectToAction("Details", new { id = id }));
    },
    ex =>
    {
        TempData["Error"] = ex.Message;
        return RedirectToAction("Details", new { id = id });
    });
}

The service throws the BusinessRuleException when the student is already enrolled (Part 5), and the Execute of the base controller (Part 7) gives the exception to the second lambda, which shows the message. It is the same Post-Redirect-Get flow which we have seen in Part 6.

Partial views and child actions

A partial view is a view without the layout, which is meant to be included in the other views. We used one already, the _Form.cshtml of the create and edit screens. The name starts with the underscore as the convention. It is rendered with Html.Partial("_Form"), and it receives the model of the parent view, or another model if we pass it.

A partial view can only display the data which the parent gives it. When the piece has its own data, like the total of the students which is shown in the list, we need a child action. It is a normal action which is marked with [ChildActionOnly], so a browser can’t call it by the URL, and which returns a partial view,

[ChildActionOnly]
public ActionResult Summary()
{
    return PartialView("_Summary", _service.Count());
}
@model int

<p class="summary">Total students: <strong>@Model</strong></p>

The parent view includes it with @Html.Action("Summary"). The framework calls the Summary action in the middle of the rendering of the list, and puts its output in the place. The following diagram shows how all the parts fit together.

How the layout, the view, the partial views and the templates fit together
How the layout, the view, the partial views and the templates fit together

You can see the result on the top of the student list,

The student list with the summary of the child action
The student list with the summary of the child action

Must Be Aware: A child action runs the whole controller pipeline again, including the database call of the service, for every request of the page. It is fine for a small widget, but don’t use it for something which can be given by the parent action in the model. For a part which is only a markup, a partial view is cheaper.

Display and editor templates

How should a DateTime be shown? If every view formats it with ToString("dd MMM yyyy"), the format is repeated and one view will surely differ. A display template solves it. The MVC looks for a view with the name of the type in the Views/Shared/DisplayTemplates folder, and uses it whenever we write Html.DisplayFor for a property of that type,

@model DateTime?
@if (Model.HasValue)
{
    <time datetime="@Model.Value.ToString("yyyy-MM-dd")">@Model.Value.ToString("dd MMM yyyy")</time>
}

This is the file Views/Shared/DisplayTemplates/DateTime.cshtml. Now the views write only,

<td>@Html.DisplayFor(m => student.DateOfBirth)</td>

and every date of the application has the same format, and the HTML5 time tag. To change the format for the whole application, we change one file. The editor templates in the EditorTemplates folder work in the same way for Html.EditorFor. A template can also be selected by the name with the [UIHint("Name")] attribute on a property.

HTML tags with TagBuilder

The built-in helpers don’t know our business. The grade of an enrollment should be a coloured badge, in two screens, the details of a student and the details of a course. We write our own helper, which is an extension method of HtmlHelper, and it builds the tag with the TagBuilder. The following diagram shows how it works.

How a custom HTML helper produces the markup
How a custom HTML helper produces the markup
public static class HtmlHelpers
{
    // <span class="grade grade-a">A</span>
    public static MvcHtmlString GradeBadge(this HtmlHelper html, string grade)
    {
        var tag = new TagBuilder("span");

        if (string.IsNullOrEmpty(grade))
        {
            tag.AddCssClass("grade-none");
            tag.SetInnerText("-");
        }
        else
        {
            tag.AddCssClass("grade-" + grade.ToLowerInvariant());
            tag.SetInnerText(grade);
        }

        tag.AddCssClass("grade");

        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
}
  • The TagBuilder gives the methods for the attributes and the CSS classes, and it renders the tag, so we don’t concatenate the strings with the quotes. The AddCssClass adds the new class to the front, which is why the grade class is added last and comes first in the output.
  • SetInnerText encodes the text, so a grade which has a < is not a script injection. The InnerHtml property is not encoded, use it only for the markup which we built ourselves.
  • The return type is MvcHtmlString. It tells Razor that the text is already HTML, and it must not be encoded again. If we returned a string, the user would see the tag as text.
  • The namespace of the class (SMS.Web.Infrastructure) must be imported in the Views/Web.config, then every view can write @Html.GradeBadge(enrollment.Grade).

The view code is one line, and the CSS decides the colours,

<td>@Html.GradeBadge(enrollment.Grade)</td>
.grade { display: inline-block; padding: 2px 8px; border-radius: 10px; font-weight: bold; color: #fff; background: #8a8a8a; }
.grade-a { background: #00a37a; }
.grade-b { background: #2b7fd0; }
.grade-c { background: #e08a00; }

The result is in the screen of the enrollment above, where the grade B is the blue badge and the course without a grade shows the grey dash. A second helper of the sample builds the Previous and Next links of the student list. It gets the URL from the caller as a function, so the helper doesn’t need to know the routes,

public static MvcHtmlString PagerLinks(this HtmlHelper html, int page, bool hasNext, Func<int, string> pageUrl)
{
    var pager = new TagBuilder("p");
    pager.AddCssClass("pager");

    var inner = string.Empty;

    if (page > 1)
        inner += Link("Previous", pageUrl(page - 1));

    inner += "Page " + page;

    if (hasNext)
        inner += Link("Next", pageUrl(page + 1));

    pager.InnerHtml = inner;
    return MvcHtmlString.Create(pager.ToString(TagRenderMode.Normal));
}

and the view uses it with a lambda (Part 5),

@Html.PagerLinks(page, Model.Count == pageSize, p => Url.Action("Index", new { term = ViewBag.Term, page = p }))

Because the helper is a normal static method, we can unit test it. We need a HtmlHelper object, but it is enough to create one with the empty context,

[Test]
public void GradeBadge_RendersASpanWithTheGradeClass()
{
    var html = new HtmlHelper(new ViewContext(), new ViewPage());

    var result = html.GradeBadge("A").ToString();

    Assert.AreEqual("<span class=\"grade grade-a\">A</span>", result);
}

Razor declarative helpers

An HTML helper is a C# method, and the markup is written as a string in it. When the reusable piece is mostly the markup, the Razor @helper is simpler. It is a function which is written with the Razor syntax, in a view. The details view of a student shows the credits as “3 credits” or “1 credit”,

@helper Credits(int credits)
{
    <span>@credits credit@(credits == 1 ? "" : "s")</span>
}

<td>@Credits(enrollment.Course.Credits)</td>

The @helper is available only in the view where it is written, and for the helpers which are shared by many views, the C# HtmlHelper extension method is the better place. A rule of thumb to choose, an extension method is for the reusable and testable pieces of the whole application, a @helper is for the small formatting of one view, and a partial view is for a bigger block of the markup.

Wrap up

In this article, we have looked at the layouts and the sections, the three ways of passing the data to a view, the built-in HTML helpers, the partial views and the child actions, the display templates, our own HTML helpers with TagBuilder, and the Razor @helper. I appreciate your time and efforts to read this article. In the next article, I will walk you through the filters, the model binding and the validation, which complete the request pipeline of the MVC.

Related Posts