Unlike normal HTML helper functions, the template helper function does not need to specify the type of HTML used, and MVC infers the choice of the appropriate HTML element, which gives us more flexibility.
Using Template helper Functions
We continue with the following example using the data model and controller in the ASP. NET MVC 4 (vi) HELP function, overwriting the edit input view after using the template helper function:
@model helpermethods.models.person@{viewbag.title = "Createperson";}
Here you use the template Help function editor and EDITORFOR,MVC to guess the corresponding data type to generate the appropriate type of input HTML markup:
...type= "Number"value= "0"/> </div> <div class= "Dataelem" > <label>first name</label> <input class= "Text-box single-line" id= "FirstName" name= "FirstName"type= "Text"Value= ""/> </div> <div class= "Dataelem" > <label>last name</label> <input class= "Text-box single-line" id= "LastName" name= "LastName"type= "Text"Value= ""/> </div> <div class= "Dataelem" > <label>Role</label> <input class= "Text-box single-line" id= "role" name= "role"type= "Text"Value= "Admin"/> </div> <div class= "Dataelem" > <label>birth DATE</LABEL&G T <input class= "Text-box single-line" id= "BirthDate" name= "BirthDate"type= "datetime"Value= "01/01/0001 00:00:00"/> </div> <input type= "Submit" value= "Submit"/> </form> ...
The HTML5 specification defines that the input tag can edit common types, such as numbers, dates, different browsers support HTML5, and the result in opera is rendered as an edit space with the spin button. DateTime is a date/time editor with an optional calendar that renders as private.
The following is a list of the template helper functions available for MVC:
Help function |
Example |
Description |
Display |
Html.display ("FirstName") |
Renders a read-only HTML element, selecting the applicable HTML element based on the data type and metadata |
Displayfor |
Html.displayfor (x = x.firstname) |
Strongly typed form of display |
Editor |
Html.editor ("FirstName") |
Renders editable HTML elements, selecting the applicable HTML elements based on data type and metadata |
Editorfor |
Html.editorfor (x = x.firstname) |
The strongly typed form of editor |
Label |
Html.label ("FirstName") |
Render <label> label based on referenced model object properties |
Labelfor |
Html.labelfor (x = x.firstname) |
Strongly typed form of label |
This example shows us how to use display and label:
@model helpermethods.models.person@{ viewbag.title = "Displayperson";}
HTML Results for output:
... <div class= "Dataelem" > <label for= "PersonId" >PersonId</label> </div> <div class= " Dataelem "> <label for=" FirstName ">FirstName</label> Adam </div> <div class=" Dataelem "> <label for= "LastName" >LastName</label> Freeman </div> <div class= "Dataelem" > <label for= " Role ">Role</label> Admin </div> <div class=" Dataelem "> <label for=" BirthDate ">birthdate </label> 01/01/0001 00:00:00 </div> ...
Integral Model Template Helper functionsThe above template helper functions can handle individual model object properties, and MVC also provides a set of template helper functions to generate HTML for the entire model object:
Help function |
Example |
Description |
Displayformodel |
Html.displayformodel () |
Generate read-only HTML rendering for the entire model object |
Editorformodel |
Html.editorformodel () |
Generate editable HTML rendering for the entire model object |
Labelformodel |
Html.labelformodel () |
Generate <label> label for entire model object |
The view of editing person after using the Integral Model helper function can be simplified to:
MVC generates the appropriate HTML editing elements for each property of person, and enumeration types are also rendered as a simple edit box, which is not very useful, and we are more accustomed to selecting the enumeration values from the drop-down boxes (we can see how to do that later). Also not all attributes, such as the Address property, which is not a C # meta-type, are not visible in the resulting results, we can expand the display of it (the object template that we can see later) for address in a editfor call:
@model helpermethods.models.person@{ viewbag.title = "Createperson";}
The strong type of editfor is used here to ensure that the generated HTML element contains the correct ID and name, such as Homeaddress.line1 generation Id= "Homeaddress_line1", name= "Homeaddress.line1" , which ensures that data is properly bound to the data model after it is committed.
Using model metadataEditorformodel () generated HTML is not so perfect, this can not blame the template helper function, it has been to show the results of the best guess, we can give the template help function metadata more hints. For example PersonID we are not able to edit, we can use the Hiddenattribute tag:
Editorformodel renders a read-only INPUT element:
If we want to not show PersonID at all:
[Hiddeninput (displayvalue=false)]
Html.editorformodel () generates a hidden INPUT element that we do not see, but is still included in the submitted data. If we want to completely ignore an attribute, not even the hidden INPUT element is generated:
It is important to note that Scaffoldcolumn (false) is only useful for Editorformodel (), a template helper function for a single property such as @Html. Editorfor (M = M.personid) will still produce the result, Unaffected by Scaffoldcolumn.
We can also set the label content generated by the label helper function in metadata way:
[DisplayName ("New person")] [Display (Name= "First")] = "Last")][Birth Date]][Display (Name= " Approved ")]
The label helper function uses the name "New person" defined by DisplayName to generate a label label for the entire model, using the name in display to generate a label label for each property.
We can use the DataType attribute to specify the data type of the property:
Public DateTime BirthDate {get; set;} ...
By specifying the Birthdate data type to date, the resulting HTML edit box contains only the date part. The available data types are:DateTime, Date, Time, Text, PhoneNumber, Multilinetext, Password, Url, EmailAddress. The template helper function generates different label elements based on different choices of data types, such as multilinetext to generate textarea multi-line edit boxes.
In addition to specifying the data type of a property by Datetype, we can also use the UIHint attribute to explicitly specify a helper function to generate HTML-selected tag elements:
... [Display (name= "first")] [UIHint ("Multilinetext")] public string FirstName {get; set;} ...
This is explicitly specified as FirstName using a textarea edit box, Editorfor and Editorformodel refer to this feature. The UI templates that you can specify include:
UIHint templates |
Editor output results |
Display output Results |
Boolean |
BOOL value generates a check box, bool? Generates a selection box containing the true, false, not set three options |
Same as editor but with disabled property prevents editing |
Collection |
Select the appropriate target generation results for each project in IEnumerable, the project is not necessarily the same type |
Equivalent editor |
Decimal |
Generates a single-line textbox type INPUT element, formatted with 2 decimal points |
Display a string with 2 decimal points |
Datetime |
Generates an INPUT element of type=datetime that contains the date and time |
Show date and time |
Date |
Generates an INPUT element of type=date, containing only the date |
Show Date |
EmailAddress |
Generate INPUT element for a single-line textbox |
Generate a element, Href=mailto: |
Hiddeninput |
Generate a hidden INPUT element |
Generate hidden input |
Html |
Generate INPUT element for a single-line textbox |
Generate a element tag |
Multilinetext |
Generating TEXTAREA elements |
Show data |
Number |
Generate the INPUT element for Type=number |
Show data |
Object |
Expands the object to produce the appropriate elements for each property of the object, and the expansion cannot be recursive, that is, if a property is not a basic type then expand |
Password |
A single-line textbox that generates a password type |
Show the data after obfuscation |
String |
Generate INPUT element for a single-line textbox |
Show data |
Text |
Same string |
Same string |
Tel |
Generate the INPUT element for Type=tel |
Show data |
Time |
Generates an INPUT element of type=time, showing only the time |
Show Time Data |
Url |
Generating a single-line INPUT element |
Generates a element, both internal HTML and HREF attributes are set to numeric values |
It is important to note that if the selected UI template and data type conflict result in an exception, such as selecting a Boolean UI template for the string data type.
We do not need to edit the metadata property directly on the model class, especially those of the ORM auto-generated model class, rebuild the model class every time the data schema is modified, the metadata on the model class are cleared, we have to re-edit the metadata, In this case we can define the model class as partial and put the metadata into a separate partner class:
[Metadatatype (typeof (Personmetadata))] public, partial class person {public int PersonId { Get Set public string FirstName {get; set;} public string LastName {get; set;} Public DateTime BirthDate {get; set;} Public Address homeaddress {get; set;} public bool isapproved {get; set;} Public role role {get; set;} }[displayname ("New person")] public partial class Personmetadata {[Hiddeninput (displayvalue=false)] Publ IC int PersonId {get; set;} [Display (name= "first")] public string FirstName {get; set;} [Display (Name = "Last")] public string LastName {get; set;} [Display (Name = "Birth Date")] public DateTime BirthDate {get; set;} [Display (name= "approved")] [UIHint ("Boolean")] public bool isapproved {get; set;} [UIHint ("Boolean")] public role role {get; set;} }
There is no need to include each attribute in the partner class, we can set metadata only for the desired property.
customizing edit Templates
We can further control the HTML results generated by the template helper function by creating a custom template, MVC looks for a custom template under the/views/shared/editortemplates directory, and we can create a strong partial view of the data type, such as the role enum type , we create role.cshtml for it:
This creates a drop-down selection dialog for the role type, and MVC searches for the custom template and uses it before using the built-in template. MVC searches in a certain order using the appropriate template:
- The template specified in the Help function, such as the MyTemplate template specified by the html.editorfor (m = = M.someproperty, "MyTemplate")
- Target specified in metadata UIHint
- Templates for data type determination, such as datatype features
- The name of the data type class being processed
- Using built-in string templates for simple types
- If the data type implements IEnumerable, use the built-in collection template
- When the above fails, use the Ojbect template to expand, expand cannot recursively, that is, do not expand the properties of the subtype
Depending on the order of the template searches above, you can make the role template more extensive, and we create a template that applies to the enum type:
@model enum@html.dropdownlistfor (m = m, Enum.getvalues (Model.gettype ()) . Cast<enum> () . Select (m + = {string enumval = Enum.getname (Model.gettype (), m); return new SelectListItem () { Selected = (model.tostring () = = Enumval), Text = enumval, Value = Enumval } ; }))
We specify the role attribute in the metadata partner class to use this enum template:
[DisplayName ("New person")] Public partial class PersonMetaData1 { ... [UIHint ("Enum")] Public role role {get; set;} }
And what if we created a template with the same name as the built-in? MVC uses our custom templates instead of built-in templates, such as BOOL and bool, to create a template that overrides the Boolean built-in type:
@model bool @if (ViewData.ModelMetadata.IsNullableValueType && model = = NULL) { @:(True) (False) <b> ( Not set) </b>,} else if (model.value) { @:<b> (True) </b> (False) (not set)} else { @:(True) <b& gt; (False) </b> (not Set)}
The above is a summary of the contents of the fourth edition of the Apress Pro ASP. NET MVC 4, as described in the original http://www.apress.com/9781430242369.
ASP. NET MVC 4 (vii) Template helper function