ASP. net mvc Model binding (5)

Source: Internet
Author: User

ASP. net mvc Model binding (5)Preface

The previous sections describe the location where IValueProvider is obtained and the generation process. This article will provide a basic example of IValueProvider's use, after reading this article, you will have a clearer impression on IValueProvider.


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


Application scenarios of IValueProvider

Figure 1

Figure 1 shows a simple example of IValueProvider to be demonstrated in this article. Here we will not explain the type in the figure. You will know the sample code below.

First, the main process is shown in the red box. Let's implement it first:

1.Controller method definition

Code 1-1

namespace MvcApplication.Controllers{    public class ValueProviderCaseController : Controller    {        public ActionResult Index(string ValueProviderCase)        {            ViewBag.value = ValueProviderCase;            return View();        }    }}

Code 1-1 defines an Index () method, and the parameter type (Model type) is string type, and the parameter name (Model name) is ValueProviderCase, remember that this parameter name will be used later.


2.View rendering code

Code 1-2

@{    ViewBag.Title = "Index";}

Code 1-2 is the view rendering code. The ViewBag dynamic type is used to transmit values.

As shown in figure 1, before executing the Controller method, you must first obtain the Model binder and then execute the Model binder, let's put some processes for getting the Model binder first. Let's take a look at the process for executing the Model binder.


3.Custom value provider Definition

As shown in figure 1, in the process of executing the Model binder, the user-defined value provider MyCustomValueProvider is executed. Here, let's take a look at the definition of this type:

Code 1-3

Using System. web. mvc; namespace MvcApplication. valueProvider {public class MyCustomValueProvider: IValueProvider {public bool ContainsPrefix (string prefix) {if (prefix = "ValueProviderCase") {return true;} return false ;} public ValueProviderResult GetValue (string key) {return ContainsPrefix (key )? New ValueProviderResult ("this is a value provider example", null, System. Globalization. CultureInfo. InstalledUICulture): null ;}}}

When I see the definition of MyCustomValueProvider in code 1-3, my friends don't have to wait for me to explain it slowly. First, the MyCustomValueProvider type implements the IValueProvider interface type, which is required. For the definition of the IValueProvider interface type, I will not put the code, that is, two methods of the MyCustomValueProvider type.

The ContainsPrefix () method indicates that the value provider determines whether it contains a specified prefix and considers the value provider as a data source, which contains the key and value. This ContainsPrefix () the method is used to determine whether the specified key exists. If yes, the GetValue () method returns the corresponding value (in our example, ContainsPrefix () only a logical judgment is made to determine whether the parameter name [Model name] of the Current Controller method is ValueProviderCase ).

The GetValue () method also indicates that it is used to return the value of the specified prefix (the value of the specified key ), in our example, only "this is a value provider example" is returned ". Some may find that the return type of the GetValue () method is not the String type, but the ValueProviderResult type. This is a good thing for the MVC framework, that is, it requires us to forcibly encapsulate our return values, there is no way to encapsulate it by human encapsulation. Let's take a look at the definition of the ValueProviderResult type:

Code 1-4

Public class ValueProviderResult {protected ValueProviderResult (); public ValueProviderResult (object rawValue, string delimiter, CultureInfo culture); public string attemptedValue {get; protected set;} public CultureInfo Culture {get; protected set;} // Abstract: // obtain or set the original value provided by the value provider. //// Return result: // original value. Public object RawValue {get; protected set;} public object convertize (Type type); public virtual object convertize (Type, CultureInfo culture );}

See the ValueProviderResult Type constructor definition in code 1-4 and comment out the RawValue attribute. Then, let's look at the Code definition of the GetValue () method in code 1-3 at a glance.


4.Custom value provider factory Definition

Switch back to the main process. When we use the custom value provider in the Model binder, we also need to think back to the previous article about the origin of the custom value provider, the custom value provider is generated by our custom value provider factory and then registered to the system's ValueProviderFactories. in Factories, then the ValueProviderFactories will be generated from the ValueProviderFactories when the ModelBindingContext type instance is generated before the Model binder is executed. the custom value provider (MyCustomValueProvider type) obtained in Factories is assigned to the ValueProvider attribute of the ModelBindingContext type instance (you can view the previous process here ).

Now let's take a look at the custom value provider factory definition, code 1-5.

Code 1-5

using System.Web.Mvc;namespace MvcApplication.ValueProvider{    public class MyCustomValueProviderFactory:ValueProviderFactory    {        public override IValueProvider GetValueProvider(ControllerContext controllerContext)        {            if (controllerContext.Controller.GetType().Name == "ValueProviderCaseController")            {                return new MyCustomValueProvider();            }            return null;        }    }}

In code 1-5, the GetValueProvider () method is added with a logic judgment. To instruct this factory to only serve the ValueProviderCaseController controller, we will not talk about it much here.



Return to the main process again. As mentioned above, Let's first look at the Model binder Execution Section. Now let's look at the Model binder acquisition section of the process. Let's just look at the definition of the custom Model binder. Code 1-6.

Code 1-6

namespace MvcApplication.Binders{    public class ValueProviderModelBinder : IModelBinder    {        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)        {            return bindingContext.ValueProvider.GetValue(bindingContext.ModelName).RawValue;        }    }}

In code 1-6, the ValueProvider attribute in bindingContext has reference to the value provider. The GetValue () method in code 1-3 is called and the parameter name is passed for logical judgment. Finally, the defined value is directly returned through the RawValue of the ValueProviderResult type returned.


6.Register the custom "mess" typeMVCIn Framework

The definitions of the above types are still not enough. We also need to register them into the system, and we use the Global. the asax file is added. Of course, you can also register it during the Controller activation process and customize a specific Model Binder for a specific controller. Of course, it is not clear that it is not practical in actual project development, it just feels like Global. the asax file will be "clean. Let's see the registered code Definition 1-7.

Code 1-7

ModelBinders.Binders.Add(typeof(string), new Binders.ValueProviderModelBinder());ValueProviderFactories.Factories.Insert(0, new ValueProvider.MyCustomValueProviderFactory());

Add code 1-7 to the Application_Start () method. First, register our custom Model binder with the system, and then add the custom value provider factory to the system, here we use the Insert () method to add it. The purpose is to keep this factory in the first place by default, saving time for further judgment. You can also use the Add () method, but it is added to the end.

Finally, let's take a look at the result diagram:

Figure 2



Author: 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: 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.