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 21B. Display Templates in MVC

Display templates are templated helpers that enable you to build a user interface based on your data model. In this lesson I show you how to use display templates to display the data in your model.

Here are the three helper methods in the DisplayExtensions class:

  • Display() — This helper returns HTML markup for a particular property in the model where the property is identified via a string expression.

  • DisplayFor() — This helper also returns HTML markup for a particular property in the model. However, with this helper, the property is identified via a strongly-typed expression.

  • DisplayForModel() — This helper returns HTML markup for all of the simple properties in the model.

    Note

    The expression DisplayFor(model => model) is equivalent to DisplayForModel().

THE DISPLAYFORMODEL HELPER

Figure 21B-1 shows the Entity Data Model (EDM) that I use in this lesson.

FIGURE 21B-1

Figure 21B.1. FIGURE 21B-1

This is the Details action method:

//
// GET: /Task/Details/5

public ActionResult Details(int id = 1)
{
    var task = (from t in _entity.Tasks
                where t.Id == id
                select t).FirstOrDefault();

    return View(task);
}

In the preceding action method I have set the default value of the id parameter to 1. This is the View that uses the DisplayForModel helper:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Lesson21b.Models.Task>" %> ...

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