Asp. NET no magic--asp.net MVC Model binding parsing (previous)

Source: Internet
Author: User

The previous article describes the model binding and validation features in ASP. NET MVC, with no magical spirit of ASP, this chapter will analyze how ASP. NET MVC can do the model binding and validation from the point of view of the code, and understand its rationale.

The main contents of this article are:
Modelbinder
Valueprivoder
Modelmetadata
Simple models and complex models
Summary

Modelbinder

Modelbinder is an ASP. NET MVC is used in the core components of model binding, and all Modelbinder implements the Imodelbinder interface, such as:

  

The interface has only one method, which is to complete the model binding based on the controller and the binding context.
There are different modelbinder in ASP. NET MVC, which are used to bind different types of data, such as normal. NET objects, HTTP uploaded files, and so on.
The following 5 types of Modelbinder are available by default:
Defaultmodelbinder: The default model binder, which typically submits requests from the browser, will use the default processor to bind the model.
Httppostedfilebasemodelbinder:http File Model Bindings
Bytearraymodelbinder: Binds binary data.
Linqbinarymodelbinder: Binds the request to the System.Data.Linq.Binary object. Reference: Http://stephenwalther.com/archive/2009/02/25/asp-net-mvc-tip-49-use-the-linqbinarymodelbinder-in-your
Cancellationtokenmodelbinder: Provides a mechanism for propagating the cancellation of model binding operations.

All Modelbinder are managed by a dictionary called Modelbinderdictionary , which exists in the definition of the controller type, as shown in, it is a protected internal property, to complete model binding when the controller executes :

  

Definition of Modelbinderdictionary:

  

It can be seen from the definition of modelbinderdictionary that it implements a dictionary interface with type key, a value of imodelbinder type, and a collection interface that dynamically increases or decreases the modelbinder according to the Modelbinder type. In addition, there is a defaultbinder, in general the example of its operation is as follows:

  

The Modelbinder dictionary in the controller contains the 5 Modelbinder described above. For more information on customizing Modelbinder, refer to: https://www.cnblogs.com/Cwj-XFH/p/5977508.html

Valueprivoder

In the previous article, it was introduced that the model bindings for ASP. NET MVC can get data from data sources such as form data, Query string, and route data, because there is a dedicated data provider for each data source to get data from the data source. There is an interface for defining a value provider in ASP. Ivalueprovider:

  

The

Core method getvalue a key to get the value, and Containsprefix determines whether the provider refers to a data source that contains a key prefixed with the specified string.
Direct implementation the interface has 3 types:
Namevaluecollectionvalueprovider: A collection of data that is stored together by name and value. You can use the name .
Dictionaryvalueprovider<tvalue>: The dictionary key is unique through the collection of generic dictionaries that store data by key-value pairs, in other words through Key.
Valueprovidercollection: A special value provider that contains all the relevant value providers , which in model bindings is the way the list is traversed, Call the Get value method of the correlation value provider to complete the data acquisition.

As I said before, there is a specific value provider for different data sources, how are these providers implemented? They are implemented according to the characteristics of the Namevaluecollectionvalueprovider and dictionaryvalueprovider<tvalue> types, which are classified as follows, There are 7 different data sources for a value provider:
Namevaluecollectionvalueprovider:
0JQueryFormValueProvider: Used to get the form value formatted by jquery.
0FormValueProvider: Used to get the value of the form form.
0QueryStringValueProvider: The value used to get the query string.
Dictionaryvalueprovider<tvalue>
0ChildActionValueProvider: The value used to get the child action method.
0JsonValueProvider: Used to get the value transferred in JSON format in the request ( Note: There is no value provider of that type, The JSON value provider creates a dictionary value provider for the dictionaryvalueprovider<object> type directly from Jsonvalueproviderfactory .
0HttpFileCollectionValueProvider: Used to get file data from a collection of files in an HTTP request.
0RouteDataValueProvider: Used to get values from route data
All of the value providers are created by the corresponding factory, and by default there are 7 value provider factories in ASP, which correspond to the 7 value providers above, and their implementation interfaces are defined as follows:

  

The Getvalueprovider method of each factory gets the corresponding value provider.
All provider factories are maintained in MVC by a type called valueproviderfactories, which maintains a static, read-only provider factory list in a hard-coded manner:

  

Run-time results, a total of 7 factories:

  

is the operating state of ASP. NET MVC in the case of a controller that is not specially configured:

  

Is the status of sending a JSON-formatted POST request, and Valueprovider has a dictionary value provider for getting JSON data:

Initiating the requested content:

  

The value provider in the request has a dictionaryvalueprovider<object> type that is used to provide JSON data compared to the previous one:

  

Modelmetadata

Metadata is a metadata that describes the data, and here is the model, which means that the data describing the model data is defined for a model in asp:

The code can be described in a language like this:
The object has 3 properties.
Where username is a string type, required and formatted in the email format, the display name is the user name.
Password and ConfirmPassword are both string types, and the types are passwords, which, in addition to the display name, ConfirmPassword also need to be compared to password, and if different, give appropriate error prompts.

In MVC, the model is described by Modelmatedata, first look at the Modelmetadata type in ASP. NET MVC:

  

    

You can see some descriptive information such as whether it is read-only, required, model type, attribute (also modelmetadata type), presentation name, complex type, and so on. In other words , ASP. Modelmetadata can be used to describe whether the properties of the model are read-only, required, type, etc., and even includes a model validator to validate the legitimacy.
It is important to note that the model type itself is described by a modelmetadata, and the properties of the type are also described by modelmetadata, meaning that the structure of the Modelmetadata description type is the same as the corresponding class structure.

Note: Modelmetadata involves the rendering of the view, and the contents of the view are described in subsequent articles.

Simple models and complex models

There is a property named Iscomplextype in the Modelmetadata type that indicates whether the type is a complex type, and what is a complex type? What are the simple types that correspond?

  

is the implementation code for Iscomplextype, with two points at its core:
1. Obtain a converter with the current model type ( Note: TypeDescriptor is a type that is used to obtain information about the type, such as attributes, attributes, events, and, of course, the type converter, which is defined in the TypeDescriptor section ).

  

  

2. After getting to the type converter, the converter determines whether the type can be converted from a string, if so it is a simple type otherwise a complex type . (defined for parts of TypeConverter)

  

Knowing the difference between a simple type and a complex type, what does it mean in MVC?
First of all, for ASP. NET MVC, the HTTP request it receives, regardless of the header, body, etc., is essentially a string, then the data extracted from the HTTP protocol is also a string, but for the MVC action method, the arguments it accepts may be strings, It can also be a number, time, and other types, so there is a conversion from string to other types, and the purpose of simple type is that MVC model binding can be directly based on the name from Valueprovider to get the value (a string), The string is then converted to the desired type through a type converter .
Here are some of the "rightfully" type converters:
Number: is the base class of a digital converter, and its implementation of the CanConvertFrom method directly hardcoded the ability to convert a numeric type from a string type (there are specific implementations of different numeric types, no longer described here).

Time: The same time type can also be converted from a string.

  

Boolean: Boolean type can be converted from a string.

  

Why do you say "take it for granted"? Because in the actual development of an action requires a time parameter, then fill in the form or through some JS components to select a date, and then submit to the server this filling time "is" a time type, fill in the number is also the number type, everything is taken for granted. But for the purpose of not "magic", it is necessary to know that even the simplest Boolean type actually does the conversion work , which is the conversion code of the Boolean converter:

  

The way in which simple and complex models are bound in MVC is different, and it is easy to understand that a simple model requires only a single string to complete the transformation , and that complex models require more action.
Another usage in ASP. NET MVC is to customize the conversion of special-format strings to specific objects, the usual example being the conversion of coordinates (latitude and longitude), which defines the user-registered Registerviewmodel using a comma-delimited string format:
1. Create a Registerviewmodel converter, inherit the TypeConverter type and overload the CanConvertFrom and ConvertFrom methods:

  

2. Use the TypeConverter feature on the Registerviewmodel type for this converter:

  

3, through the Postman simulation request:

   

  Note: Model is the action parameter name.
Action is able to get the data correctly:

  

Summary

This article mainly introduces the main components and concepts of model binding in ASP. Valueprovider provides data, modelmetadata description data, Modelbinder binding data, data validation that is indispensable in the process of binding data, The conversion function corresponds to the modelvalidation and TypeConverter types respectively. The next article describes how ASP. NET MVC implements the logic for model binding when the controller executes.

PS. Because of the length of the model binding parsing content is divided into two, the next article will be organized and issued as soon as possible. I wish you a Happy Lantern Festival (* ^_^ *)

Reference:
Http://stephenwalther.com/archive/2009/02/25/asp-net-mvc-tip-49-use-the-linqbinarymodelbinder-in-your
Https://www.cnblogs.com/Cwj-XFH/p/5977508.html

This article link: http://www.cnblogs.com/selimsong/p/8484482.html

Asp. NET no magic--Directory

Asp. NET no magic--asp.net MVC Model binding parsing (previous)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.