Series directory
Preface
Model is one of the powerful MVC mechanisms. It is the core mechanism of data interaction between clients and servers in the MVC framework. An in-depth understanding of the model helps us to expand on the basis of MVC, and also helps us create software modules with more reuse significance. It mainly includes the following topics:
- Templated view helpers: Generate HTML control elements based on the model
- Model binding: automatically maps and parses user-submitted data
- Integrating validation: Integrated Client Authentication
We know ASP. NET web applicationsProgramThe data interaction is actually the conversion between the client form data and the. NET object (model. This problem is explained:
In MVC, many HTML helper are responsible for converting the model into an HTML Tag, and model binding converts the data submitted by the user into a model.
Templated view helpers
The newly added templated view helpers in MVC2 refers to extension methods like HTML. textboxfor. Using this method to construct HTML elements such as link forms is very convenient and intelligent. These methods automatically determine the HTML elements to be converted based on the type of the model or model attribute, and automatically enable model binding.
for example, if you have an attribute named approved and it is of the bool type, HTML. editorfor (x => X. Approved) will be converted into a check box. For example, when HTML. when editorfor (), MVC you need to select an appropriate template for rendering , therefore, a template can be understood as a predefined HTML representation of a data structure. The following Code is extracted from templatehelpers:
Static readonly dictionary <string, func
you can see the built-in templates. In general, HTML elements can be divided into two types: Display and editing. There are two main types of helper, displayxxx, labelxxx, and editorxxx respectively. The MVC Framework includes defadisplaydisplaytemplates and defaulteditortemplates to complete the render work. The templatehelpers class is responsible for deploying and using the template. The built-in templates of MVC are mainly simple types. For complicated types of MVC, you can customize templates by yourself. A Custom template is actually to create ascx and then put it in the appropriate position, which is searched by the view engine. The Framework reviews the ascx files in the /views/shared/displaytemplates/ and /views/shared/editortemplates/ directories, and regard it as custom template loading, so we can design a complicated ascx template, regard it as a user control, and then simply use various methods of templatehelper to load, this is also a way to replace partialview or childaction . Here, the ascx file name should correspond to the type name as much as possible. Therefore, we can create a datetime. ascx and edit the Code as follows to "overload" the template of the datetime Data Type Built in MVC.
<% @ Control Language = "C #" inherits = "viewusercontrol <datetime?> "%> <%: HTML. textbox ("",/* name suffix */viewdata. templateinfo. formattedmodelvalue,/* Initial Value */New {@ class = "date-picker"}/* HTML attributes */) %>
Note that it is used hereViewdata. templateinfo. formattedmodelvalueInstead of Model. tostring (), you can make full use of the features of modelmetadata, which will be more involved in the future. You can also write it as follows:
<% @ Control Language = "C #" inherits = "viewtemplateusercontrol <datetime?> "%> <%: HTML. textbox ("",/* name suffix */formattedmodelvalue,/* Initial Value */New {@ class = "date-picker"}/* HTML attributes */) %>
Note that viewtemplateusercontrol is inherited here rather than viewusercontrol above.
Since MVC presents the UI as a template, what does it affect the choice of MVC? The following factors affect the Template Selection of the MVC framework by priority:
- The specified Template Name is displayed in the editorfor method, HTML. editorfor (x => X. someproperty, "My template ").
- Description of the metadata corresponding to the model. For example, you can add the property [uihint ("My template")]
- The data type of the metadata description of the model, such as [datatype (datatype. emailaddress)]
- The actual. Net Type of the corresponding Property
- For simple types that can be converted to string, use the string template.
- The parent class attribute of the model will also be converted.
- If the property implements ienumable, the collection template is selected.
- Finally, use the object Template
Modelmetadata
Templatehelpers is indeed the main class to complete render work, but in fact, templatehelpers is only responsible for render, it needsModelmetadataAnd modelmetadata itself is like its class name, meaning"Model metadata", Which is equivalent to an object that describes data.ModelmetadataproviderTo provide real data, you can help understand:
We can see that MVC has been built in.DataannotationmodelmetadataproviderTo act as modelmetadataprovider. It has built-in support for the data Annotation Feature in. net, suchDisplaycolum,Displayformat,RequiredDataannotationmodelmetadataprovider also supports unique MVC features such as uihint.
You can specify a modelmetadataprovider as follows: conventionsmetadataprovider.
Protected void application_start () {arearegistration. registerallareas (); registerroutes (routetable. routes); modelmetadataproviders. Current = new conventionsmetadataprovider ();}
Modelmetadataprovider itself is an abstract class that can be inherited from any of the following classes. We recommend that you inherit from dataannotationmodelmetadataprovider so that our custom modelmetadataprovider can retain the original support.
Let's take a look at the attributes and methods of modelmetadata. Some of them will be investigated by templatehelpers and affect the rendering of HTML elements. TheFromlambdaexpression ()The method is used to obtain modelmetadata from the lambda expression, which is also the method to be called by the built-in templatehelpers.
When we need to use attribute to describe the model class, we may encounter this situation. The model itself is generated by tools such as ORM and cannot be directly modified. Therefore, MVC provides[Metadatatype]Attribute to solve this situation. Generally, the automatically generated model class is a partial classification:
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 ;}}
Define another corresponding class and use the metadatatype feature to identify it. Define an internal class and mark the required feature description.
[Metadatatype (typeof (personmetadata)] public partial class person {// This class is only used as a source of metadata private class personmetadata {[hiddeninput (displayvalue = false)] public int personid {Get; set;} [displayname ("first name")] Public String firstname {Get; set;} [displayname ("last name")] public String lastname {Get; set;} // also add any other properties for which you want to supply metadata }}
Summary
The above describes the implementation of template and modelmatedata from the perspective of the framework. More details need to be paid more attention in practice. In addition, this part also involves the "model binding" mentioned in the next article. It is better to understand this part by doing more extensions.
labor fruit, reprinted please indicate the source: http://www.cnblogs.com/P_Chou/archive/2011/01/23/details-asp-net-mvc-10.html