Model Bindings for ASP (modelbinding)

Source: Internet
Author: User

modelbinding: The process of creating a. NET object with a browser that occurs in the form of an HTTP request.

First, understand the model binding.

1. The model binder is defined by the Imodelbinder interface. The following is the definition of this interface

namespace system.web.mvc{    publicinterface  imodelbinder    {        object  Bindmodel (controllercontext controllercontext, Modelbindingcontext bindingcontext);}    }

2. In an MVC program, you can have more than one model binder, and each binder can be responsible for one or more model types.

3. The model Binder is responsible for producing the parameter values of the action method, and transmits this value to the action caller, which is injected into the target's action method by the action caller.

This usually means that some elements of the requested data are to be converted, but the MVC framework has no limitations on how to obtain the data.

The process of model binding is achieved through the model binder, which is designed to create objects with the data contained in the request.

here are the steps for model binding :
(1), check the name and type of the object you want to create.

(2), find the request through the object name, and find the available data.

(3) The type of data value to be converted based on the type of object to be found.

(4) Constructs the target object by object name, object type, and processed data.

(5), the constructed object is passed to the action Invoker, and the object is injected into the action method by the action Invoker.

Second, the ASP. NET default model binder (Defaultmodelbinder)

1. An application can contain multiple model binders, but most of the values depend on the defaultmodelbinder of the binder class built into the MVC framework. By default, this model binder looks for the following 4 locations in order:

Request.form,routedata.values,request.querystring,request.files. This 4 places, as long as there is a place to find the value, back to stop the search.

2. When the argument for an action method is a simple type, Defaultmodelbinder attempts to convert the string value obtained from the request data to a value of type using the System.ComponentModel.TypeDescriptor class.

3. When the argument of an action method is a complex type (that is, a type that cannot be converted with the TypeConverter Class), Defaultmodelbinder will use reflection to get the public property collection, if binding in turn. If it is still a complex type, this procedure is executed again, getting the public property collection until all can be bound. The difference is that the names of these properties are nested (homeaddress.line1).

4. Specify a custom prefix. When the default model binder looks for a data item, you can specify a custom prefix to find for it.

Public ActionResult Register ( person Firstperson, [Bind (prefix= ' MyPerson ')] person Secondperson)

5, there is a choice of binding. We can use the bind annotation property to include or exclude model properties to the binding process.

Contains only FirstName and LastName

Public ActionResult Register ([Bind (Include= "Firstname,lastname")]person person)

Exclude Isapprove and role only

Public ActionResult Register ([Bind (Exclude= "Isapproved,role")]person person)

Third, bind to XXX (Defaultmodelbinder can handle multiple data items with the same name)

For example:

@{Viewbag.title="Address"; }@Html. TextBox ("Movies") @Html. TextBox ("Movies") @Html. TextBox ("Movies")<input type="Submit"Value="Submit"/>

3 Html.textbox the 3 input elements produced by the method are movies the values of the so-called name Tag property:

<inputID= "Movies"name= "Movies"type= "text"value="" /><inputID= "Movies"name= "Movies"type= "text"value="" /><inputID= "Movies"name= "Movies"type= "text"value="" /><inputID= "Movies"name= "Movies"type= "text"value="" /><inputID= "Movies"name= "Movies"type= "text"value="" /><inputID= "Movies"name= "Movies"type= "text"value="" /><inputtype= "Submit"value= "Submit"/>

To accept multiple data items in an action method:

[HttpPost]  Public ActionResult Index (list<string> movies) {//...}

1. Binding to a collection of custom types

What is a custom type: does not belong to. NET architecture for those known types. For example, I define how the type is a custom type.

Generates HTML by using the index number in the collection object as the predecessor to each property name of the object. You can then use the collection of custom types as parameters in the action method.

The model Binder is able to find and bind to all the data elements that are defined as long as the index values are properly generated.

2. Binding to a collection of non-serialized indexes

Use any string key to define the data item for the collection. : Simply define a hidden INPUT element named "index" to specify the key for the data item

<h4>First person</h4><inputtype= "hidden"name= "Index"value= "Firstperson"/>First Name: @Html. TextBox ("[Firstperson]. FirstName ") Last Name: @Html. TextBox (" [Firstperson]. LastName ")<h4>Second person</h4><inputtype= "hidden"name= "Index"value= "Secondperson"/>First Name: @Html. TextBox ("[Secondperson]. FirstName ") Last Name: @Html. TextBox (" [Secondperson]. LastName ")

The name of the input element of the manifest adds a predecessor ([Firstperson],[secondperson]) that matches the hidden index element. The model binder detects the index and associates it with the data values during the binding process.

3. Binding to a dictionary

The default binder is able to bind to a dictionary (Dictionary), but follows a special naming sequence.

"Hidden"Name="[0].key"Value="Firstperson"/>First Name: @Html. TextBox ("[0].value. FirstName"Last Name: @Html. TextBox ("[0].value. LastName")"Hidden"Name="[1].key"Value="Secondperson"/>First Name: @Html. TextBox ("[1].value. FirstName"Last Name: @Html. TextBox ("[1].value. LastName")

When binding to dictionary<string,person> or idictionary<string,person>, The dictionary will contain 2 person objects that are subordinate to the Firstperson and Secondperson keys. You can use the following action methods to accept data:

[HttpPost]

Public ViewResult Register (idictionary<string,person>people) {...}

Iv. call model bindings manually.

When parameters are defined for an action method, the model binding process is performed automatically. We can also manually control this process, so that we can more clearly control how to instantiate the model, where to get the data, and how to handle data parsing errors.

       [HttpPost]        public  actionresult Index ()        {            string"" ;            Updatemodel (name);             return View ();        }  

Updatemodel method The model object generated by the above statement is a parameter and attempts to obtain its value using a standard binding procedure.

One reason to invoke the model binding manually is to support dependency injection (DI) for model objects.

       [HttpPost]        public  actionresult Index ()        {            //  Added di support. But this is not the only way to join DI support            Address addressor = (address) DependencyResolver.Current.GetServices (typeof  (Address));            Updatemodel (addressor);             return View ();        }

1. Restrict binding to a specific data source

Specify a specific data source by providing an object of type Ivalueprovider to the Updatemodel method.

        [HttpPost]        public  actionresult Index ()        {            //  Added di support. But this is not the only way to join DI support            Address addressor = (address) DependencyResolver.Current.GetServices (typeof  (Address));             // limit the value of address from Request.Form            New Formvalueprovider (ControllerContext));             return View ();        

The 4 default data sources have a ivalueprovider implementation.

Data source Ivalueprovider implementation
Request.Form Formvalueprovider
Routedata.values Routedatavalueprovider
Request.QueryString Querystringvalueprovider
Request.Files Httpfilecollectionvalueprovider

The most common way to qualify a data source is to find only the form values. We can implement it in a more elegant way. You do not have to create an instance of the Formvalueprovider class.

      [HttpPost]        public  actionresult Index (formcollection formData)        {            / / add di support. But this is not the only way to join DI support            Address addressor = (address) DependencyResolver.Current.GetServices ( typeof (Address));             // limit the value of address from Request.Form             Updatemodel (addressor,formdata);             return View ();        }

2. Handle binding errors.

Users will inevitably provide some values that cannot be bound to the corresponding model properties. When we explicitly call the model binding stone, we need to be responsible for handling this kind of error.

The model binder represents a binding error by throwing a InvalidOperationException exception. The details of the error are viewed through the modelstate feature.

Therefore, when we use the Updatemodel method, we must be prepared to catch the exception and modelstate the error message to the user.

//Add the exception code method during the capture model binding process one[HttpPost] Publicactionresult Index (formcollection formData) {//added di support. But this is not the only way to join DI supportAddress address = (address) DependencyResolver.Current.GetServices (typeof(Address)); Try            {                //limit the value of address from Request.FormUpdatemodel (address, formData); }Catch(InvalidOperationException er) {//provides user interface anti-feedback based on Modelstate            }            returnView (address); }

Another method is to use the TryUpdateModel method. Returns "True" if the binding succeeds, returning "false" if unsuccessful.

//exception code method for capture model binding process two[HttpPost] Publicactionresult Index (formcollection formData) {//added di support. But this is not the only way to join DI supportAddress address = (address) DependencyResolver.Current.GetServices (typeof(Address)); //Try//{            //    //limit the value of address from Request.Form//Updatemodel (address, formData); //}catch (InvalidOperationException er)//{            //    //provides user interface anti-feedback based on Modelstate//}            if(TryUpdateModel (address, formData)) {//Normal Management            }            Else            {                //provides user interface anti-feedback based on Modelstate            }            returnView (address); }

V. Using model bindings to receive file uploads

For receiving file uploads, all you have to do is define an action method that takes the Httppotedfilebase class as the parameter type. The model binder populates it with the data corresponding to the uploaded file.

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.