How many time in ASP.net web development do you find yourself writing the same three elements for every input field – the label, the input field itself and the validation element(s).
@Html.LabelFor(x=>x.Firstname) @Html.TextBoxFor(x=>x.Firstname) @Html.ValidationMessageFor(x=>x.Firstname)
This is better than the equivalent in webforms for sure, but when a site contains hundreds of these sets of elements, changing the way they present is still an uninviting task.
The MVC team have provided a hook for site developers to create “templates” for the rendering of elements of the ViewModel. To use the template you use Html.EditorFor or Html.DisplayFor, depending on whether you are editing or simply reading the information.
This method looks for a folders either called EditorTemplates or DisplayTemplates int eh view folder hierarchy, and then tries to find the file with a name that matches the type of property being rendered. For example, if Firstname is a string, the view called String.ascx or String.chtml is sought.
The file is a partial view with the model defined as the type of property – in this case a string.
@model System.String @Html.Label("") @Html.TextBox("",Model) @Html.ValidationMessage("")
What is interesting here is that we are already in the context of a resolved property, so the ViewData property metadata is all in the correct context for the Html helpers. This means we do not need to further specify the property name. We would do that if the model was more complex, say a child entity with distinct properties of it’s own.
Model is passed into the
Html.Texbox helper in case the Model has a value set on an initial GET request (Learn more about how ASP.net MVC populates fields values, and the differences between GET and POST requests here).
With the editor template now created, I can change the initial three line of code to:
@Html.EditorFor(x => x.Firstname);
And get the label, input field and validation rendered as previously.
This quick note has demonstrated how the use of templates can reduce the mark-up in files significantly without any loss of functionality while enable easier site wide modifications. This has demonstrated the use of EditorTemplates and shown the conventions required. Similar conventions control the use of the DisplayTemplates.