ASP. net mvc Model binding (6)

Source: Internet
Author: User

ASP. net mvc Model binding (6)Preface

The previous sections provide a basic example for the use of IValueProvider, but do not provide a detailed introduction to the implementation of the IValueProvider type, however, the MVC Framework provides several default implementation types. In this article, we will explain the NameValueCollectionValueProvider type as an example, let's take a look at how the value provider provided by the MVC Framework processes the Model value.

 

Model Bind
  • IModelBinder, Custom ModelSimple implementation of the binder
  • ModelThe binder is in the MVCPosition in the framework
  • MVCDefault Model inBinding Process
  • IModelBinderProviderSimple Application
  • IValueProviderIn MVCPosition and process generated in the framework
  • IValueProviderApplication scenarios
  • IValueProviderNameValueCollectionValueProvider
Implementation of IValueProvider NameValueCollectionValueProvider

In the previous article, we demonstrated how to use IValueProvider. It is a binding process from the Controller Method to the view, have you ever wondered how the data in the view is bound back to the controller. Different Data Types in the view have different binding types. This document provides an example of binding a custom type.

Code 1-1

Public class Customer {[HiddenInput (DisplayValue = true)] public string CustomerID {get; set;} [Display (Name = "Name")] public string Name {get; set ;} [DataType (DataType. date)] [Display (Name = "registration Date")] public DateTime RegistrationDate {get; set;} [UIHint ("Address")] public Address {get; set ;}} public class Address {[Display (Name = "Address Name")] [MyCustomMetadataAware] public string AddressName {get; set ;}}

The type in code 1-1 has already appeared many times, but the attitude of being responsible for friends who have not read the previous sections should also be added. This is the example ViewModel to be used in the following example.

First, we need data presentation:

Code 1-2:

    public class ValueProviderCaseController : Controller    {        public ViewResult Show(Customer customer)        {            return View(customer);        }    }

Code 1-2 defines a Show () method. The parameter type is the type shown in code 1-1.

Take a look at the view corresponding to the Show () method. Of course, this creates a strongly typed view with code 1-3.

Code 1-3

@ Model ConsoleApplication2.Customer @ {ViewBag. title = "Show" ;}< h2> Show 

In code 1-3, we can also see that the BeginForm () view helper is used, and the form points to the Update () method of the ValueProviderCase controller. This will be mentioned later and has been taken for the moment. At this time, we still cannot run the project. We need to configure a Model Binder for Show () in code 1-2, code 1-4.

Code 1-4

Public class MyCustomModelBinder: IModelBinder {public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {if (controllerContext. httpContext. request. requestType = "GET") {return new Customer () {CustomerID = "010", Name = "tester", RegistrationDate = DateTime. now, Address = new Address () {AddressName = "City of the Sky" }};} return null ;}}

From code 1-4, we can see that the Model binder is controlled so that it returns ViewModel instances of the type shown in code 1-1 when the request type is Get. Because we will also use this Model binder in the following example, we have added control. The registration of the Model binder is not mentioned here. Result 1.

Figure 1

If we click the submit button at this time, what will the data look like? Data is transmitted to the current system context.

 

NameValueCollection

Why do we need to talk about the NameValueCollection type? Because the operation in the NameValueCollectionValueProvider type is for the NameValueCollection type. Here we can see the data presentation 2 after clicking submit in Figure 1.

Figure 2

What about the data? Don't worry. In Figure 2, the value is in the AllKeys attribute of NameValueCollection type, and the instance of NameValueCollection type is through controllerContext. httpContext. request. form is obtained in this way, that is, the data type formed after clicking "Submit. Our NameValueCollectionValueProvider type is the processing of the NameValueCollection type. The specific internal processing details are not described here.

Next we need to do the operation after submission, that is, to display the Update interface, then we have to follow the definition in code 1-3 above, we need an Update () method, sample code 1-5.

Code 1-5

    public class ValueProviderCaseController : Controller    {        public ViewResult Show(Customer customer)        {            return View(customer);        }        [HttpPost]        public ActionResult Update(Customer customer)        {            return View(customer);        }    }

At this time, we cannot see the internal implementation of the biner, so let's simulate and modify the content in code 1-4 above, such as the sample code 1-6.

Code 1-6

Public class MyCustomModelBinder: IModelBinder {public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {if (controllerContext. httpContext. request. requestType = "GET") {return new Customer () {CustomerID = "010", Name = "tester", RegistrationDate = DateTime. now, Address = new Address () {AddressName = "City of the Sky" }};} else if (controllerContext. httpContext. R Equest. requestType = "POST") {Customer customer = new Customer (); customer. address = new Address (); NameValueCollection nameValueCollection = controllerContext. httpContext. request. form; NameValueCollectionValueProvider nameValueCollectionValueProvider = new NameValueCollectionValueProvider (nameValueCollection, System. globalization. cultureInfo. installedUICulture); customer. customerID = GetValue (NameValueCollectionValueProvider, "CustomerID"); customer. name = GetValue (nameValueCollectionValueProvider, "Name"); customer. registrationDate = DateTime. parse (GetValue (nameValueCollectionValueProvider, "RegistrationDate"); customer. address. addressName = GetValue (nameValueCollectionValueProvider, "Address. addressName "); return customer;} return null;} private string GetValue (IValueProvider valu EProvider, string preFix) {return valueProvider. ContainsPrefix (preFix )? ValueProvider. GetValue (preFix). AttemptedValue: null ;}}

I forgot to mention it here. I can think of the NameValueCollection type as a set of key-value series, and the NameValueCollection type instance already contains all the data, you can use its internal GetValue method (not the GetValue method in code 1-6) to obtain the corresponding value. This method is also used to obtain the value within the NameValueCollectionValueProvider type.

In code 1-6, we have made too many changes to the Model binder. First, the controller makes too many changes to the Model binder when the request type is POST (that is, it is used to request the Update () method) using this Model binder, We instantiate a ViewModel instance shown in code 1-1, which will be assigned a value later, then we get the data in the form through the context (NameValueCollection type instance) as the parameter of the NameValueCollectionValueProvider Type constructor, we also define a private GetValue () method in the Model binder, the purpose of this operation is to obtain data from instances of NameValueCollectionValueProvider type based on the execution prefix (the key value in NameValueCollection type, that is, the Name attribute in the view element.

Now let's take a look at the view code corresponding to the Update () method. The sample code is 1-7.

@model ConsoleApplication2.Customer@{    ViewBag.Title = "Update";}

At this time, we can run the project. First, we can see the Show page, modify the values, and then we can see that the modified values have been updated to the Update interface.

 

 

Author: Jin Yuan

Source: http://www.cnblogs.com/jin-yuan/

The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and go to the Article Page.

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.