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 22B. Editor Templates in MVC

Editor templates are structured helpers that enable you to build a user interface based on your data model. In this lesson I show you how to use the editor templates to edit the data in your model.

Here are the three helper methods in the EditorExtensions class:

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

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

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

    Note

    The expression EditorFor(model => model) is equivalent to EditorForModel().

THE EDITORFORMODEL HELPER

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

FIGURE 22B-1

Figure 22B.1. FIGURE 22B-1

These are the Create action methods:

//
// GET: /Task/Create

public ActionResult Create()
{
    Models.Task task = new Models.Task();
    return View(task);
}
//
// POST: /Task/Create

[HttpPost]
public ActionResult Create(Models.Task task)
{
    if (ModelState.IsValid)
    {
        try
        {
            // TODO: Add insert logic here
            return RedirectToAction("Index");
         }
            catch
         {
            return View(task);
         }
    }
    return View(task);
}

This is the View that uses the EditorForModel helper:

<%@ Page Title="" Language="C#" ...

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