ASP. net mvc-model binding, asp. netmvc Model

Source: Internet
Author: User

ASP. net mvc-model binding, asp. netmvc Model

In this article, we will talk about Model Binding. In fact, we have a preliminary understanding of ASP. net mvc, you may have a question: why is the URL segment converted to parameters of the int type or other types? Here we have to say that the model is bound.Model binding refers to the process of creating a. NET object using the data sent by the browser as an HTTP request.Every time you define an action method with parameters, it is always dependent on this model binding process.

Prepare a project

Create an MVC project named MVCModels and create a new class file Person in the Models folder.

 1 using System; 2  3 namespace MVCModels.Models 4 { 5     public class Person 6     { 7         public int PersonId { get; set; } 8         public string FirstName { get; set; } 9         public string LastName { get; set; }10         public DateTime BirthDate { get; set; }11         public Address HomeAddress { get; set; }12         public Role Role { get; set; }13     }14 15     public class Address16     {17         public string Line { get; set; }18         public string City { get; set; }19         public string PostalCode { get; set; }20         public string Country { get; set; }21     }22 23     public enum Role24     {25         Admin,26         User,27         Guest28     }29 }

Define a Home controller.

 1 using MVCModels.Models; 2 using System.Linq; 3 using System.Web.Mvc; 4  5 namespace MVCModels.Controllers 6 { 7     public class HomeController : Controller 8     { 9         private Person[] personDate = {10             new Person { PersonId = 1, FirstName = "Adam", LastName = "Freeman", Role = Role.Admin },11             new Person { PersonId = 2, FirstName = "Jacqui", LastName = "Griffyth", Role = Role.User },12             new Person { PersonId = 1, FirstName = "John", LastName = "Smith", Role = Role.Guest },13         };14         public ActionResult Index(int id)15         {16             Person dataItem = personDate.Where(p => p.PersonId == id).First();17             return View(dataItem);18         }19     }20 }

Next, create a View File Index.

@model MVCModels.Models.Person@{    ViewBag.Title = "Index";    Layout = "~/Views/Shared/_Layout.cshtml";}

Understanding model binding

Model binding is a bridge between an HTTP request and a C # method. It creates a. NET object based on the Model type in the Action method and assigns the HTTP request data to the object after conversion. When we start the project and navigate to/Home/Index/1, we will see the following figure:

When we request/Home/Index/1 URL, the routing system assigns the last segment value 1 to the id variable. Action invoker knows through the routing information that the current request needs the Index action method for processing, but it must obtain the value of this method parameter before calling the Index action method. The default action caller ControllerActionInvoker relies on the model binder to generate the data objects required to call the action. The model binder is defined by the IModelBinder interface. In this example, the action caller checks the Index method and finds that it has an int type parameter. Therefore, the caller searches for the binding agent responsible for binding the int value and calls its BindModel method.

Use the default model Binder

Although the application can customize the model binder, it usually relies on the built-in binder class defamodelmodelbinder. When the action caller cannot find a user-defined binder of a certain type, the default model binder is used. By default, the model binder searches for four locations. See the following table:

The order in which the defamodelmodelbinder class looks up parameter data
Source Description
Request. From The value provided by the user in the HTML form Element
RouteData. Values Value obtained through application route
Request. QueryString Query string data contained in the request URL
Request. Files Files uploaded in the request

In this example, DefaultModelBinder searches for the following values for the id parameter:

1. Request. Form ["id"]

2. RouteData. Values ["id"]

3. Request. QueryString ["id"]

4. Request. Files ["id"]

Simple binding type

When processing simple parameter types, defamodelmodelbinder uses System. componentModel. typeDescriptor class: converts the character parameter value obtained from the request data to the parameter type. If the conversion fails, defamodelmodelbinder cannot be bound to the Model. For example, access to/Home/Index/apple will show:

The default model binder can see that the int value is required. If the view converts the apple value provided in the URL to the int type, an error occurs. In this case, we can modify the code, provide a default value for the parameter, so that no error will occur when the default binder cannot be converted.

1 ...  2 public ActionResult Index(int id = 1)3 {4     Person dataItem = personDate.Where(p => p.PersonId == id).First();5     return View(dataItem);6 }

Bind complex types

When the action method parameter is of the same type (that is, the type conversion attribute cannot be used with the TypeConverter class), The DefaultModelBinder class uses the reflection class to obtain the public attribute set. Now let's modify the code.

 1 using MVCModels.Models; 2 using System.Linq; 3 using System.Web.Mvc; 4  5 namespace MVCModels.Controllers 6 { 7     public class HomeController : Controller 8     { 9         private Person[] personDate = {10             new Person { PersonId = 1, FirstName = "Adam", LastName = "Freeman", Role = Role.Admin },11             new Person { PersonId = 2, FirstName = "Jacqui", LastName = "Griffyth", Role = Role.User },12             new Person { PersonId = 1, FirstName = "John", LastName = "Smith", Role = Role.Guest },13         };14         public ActionResult Index(int id = 1)15         {16             Person dataItem = personDate.Where(p => p.PersonId == id).First();17             return View(dataItem);18         }19         public ActionResult CreatePerson()20         {21             return View(new Person());22         }23         [HttpPost]24         public ActionResult CreatePerson(Person model)25         {26             return View("Index", model);27         }28     }29 }

Create a CreatePerson view.

 1 @model MVCModels.Models.Person 2 @{ 3     ViewBag.Title = "CreatePerson"; 4     Layout = "~/Views/Shared/_Layout.cshtml"; 5 } 6  7 

When the form is passed back to the CreatePerson method, the default binder finds that the action method requires a Person object and processes each attribute in sequence. The binder finds each value in the request. If one property requires another composite type, this process will be repeated. For example, in this example, the HomeAddress attribute of the Person class is of the Address type. When you search for the value of the Line attribute, the model binder looks for HomeAddress. the value of Line, that is, the combination of the property name (HomeAddress) of the model object and the attribute name (Line) of the attribute type (Address.

Bind features

We can also use the bind feature to bind the HomeAddress attribute value in the Person object to Address-type parameters, for example:

 

1 public ActionResult DisplayAddress([Bind(Prefix="HomeAddress")]Address address) 2 {3     return View(address);4 }

 

The parameter type of the DisplayAddress action method is not necessarily the HomeAddress attribute type of Person. It can be another type, as long as the type contains the City

Or Country attributes with the same name will be bound. However, note that after the Bind feature is used to specify the prefix, the name attribute of the form element to be submitted must have this prefix before it can be bound. The Bind feature has two attributes: Exclude and Include. They can specify that in the Mdoel attribute, the Binder does not search for or only looks for a certain attribute, that is, either only this attribute is included or not included in the search. The following action method:

1 public ActionResult DisplayAddress([Bind(Prefix = "HomeAddress", Exclude = "Country")]Address address) 2 {3     return View(address);4 }

At this time, the Binder will not bind a value to the Country attribute of the Model Address.

 

Related Article

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.