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 toEditorForModel()
.
THE EDITORFORMODEL HELPER
Figure 22B-1 shows the Entity Data Model (EDM) that I use in this lesson.
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#" ...
Get ASP.NET 4 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.