ASP. NET MVC Model binding (V)

Source: Internet
Author: User

ASP. NET MVC Model binding (V) Preface

The previous space for Ivalueprovider's acquisition location and the generation process is explained, this article will be a basic example of the use of Ivalueprovider to explain, after reading this article you will have a clearer impression of Ivalueprovider.

Model Binding
    • Imodelbinder, custom model binder Simple implementation
    • Location of the model binder in the MVC framework
    • The default model binder generation process in MVC
    • Simple application of Imodelbinderprovider
    • Ivalueprovider the location and process generated in the MVC framework
    • Ivalueprovider's application Scenario
    • The realization of Ivalueprovider Namevaluecollectionvalueprovider

Ivalueprovider's application Scenario

Figure 1

Figure 1 shows a simple example of the ivalueprovider to be demonstrated in this article. There is no explanation for the types in the diagram and the sample code below will be known.

First, the red box shows the main flow, let's do it first:

1. Definition of the Controller method

Code 1-1

namespace mvcapplication.controllers{    publicclass  Valueprovidercasecontroller: Controller    {        public actionresult Index (string  valueprovidercase)        {             = valueprovidercase;             return View ();}}    }

In code 1-1 It is very simple to define an index () method, and the parameter type (model type) is a string type, the parameter name (model name) is valueprovidercase, please remember that this parameter name will be used later.

2. View rendering side code

Code 1-2

@{    viewbag.title = "Index";} < H2 > Index</h2><p>@ViewBag. Value</  p>

Code 1-2 is the view rendering side code, where the ViewBag dynamic type is used to pass the value.

As you can see from Figure 1, before executing the controller method, we first get the model binder and then execute the model binder, we first put the part of the process to get the model binder and first look at the process of executing the model binder.

3. Definition of a custom value provider

As seen in Figure 1, in the process of executing the model binder, the last is the custom value provider Mycustomvalueprovider that executes, and here we look at the definition of this type:

Code 1-3

usingSYSTEM.WEB.MVC;namespacemvcapplication.valueprovider{ Public classMycustomvalueprovider:ivalueprovider { Public BOOLContainsprefix (stringprefix) {            if(prefix = ="Valueprovidercase")            {                return true; }            return false; }         PublicValueproviderresult GetValue (stringkey) {            returnContainsprefix (Key)?NewValueproviderresult ("This is a value provider example",NULL, System.Globalization.CultureInfo.InstalledUICulture):NULL; }    }}

See code 1-3 in the definition of Mycustomvalueprovider, small partners do not panic me to explain slowly, first mycustomvalueprovider type implementation of the Ivalueprovider interface type, this is necessary. For the definition of Ivalueprovider interface type I will not put the code, that is, the Mycustomvalueprovider type of two methods.

The Containsprefix () method means that the value provider internally determines whether the specified prefix is included, and the value provider is imagined as a data source that contains the key and the value, and the Containsprefix () method is used to determine whether the specified key exists. If present, the GetValue () method returns the corresponding value (in our example, here, Containsprefix () simply makes a logical decision as to whether the parameter name "model name" of the current controller method is Valueprovidercase).

The meaning of the GetValue () method is also mentioned above, which is used to return the value of the specified prefix (the value of the specified key), and in our example just returns "This is a value provider example". Some friends may have discovered that the return type of the GetValue () method is not a string type, but a valueproviderresult type, which is a good thing for the MVC framework, that is, it wants us to force the encapsulation of our return value, no way to encapsulate it cowgirl encapsulation, Little friends, look at the definition of the Valueproviderresult type:

Code 1-4

 Public classValueproviderresult {protectedValueproviderresult ();  PublicValueproviderresult (ObjectRawValue,stringAttemptedvalue, CultureInfo culture);  Public stringAttemptedvalue {Get;protected Set; }  PublicCultureInfo Culture {Get;protected Set; } //        //Summary://Gets or sets the original value provided by the value provider. //        //return Result://The original value.          Public ObjectRawValue {Get;protected Set; }  Public ObjectConvertTo (type type);  Public Virtual ObjectConvertTo (Type type, CultureInfo culture); }

See the comment for the constructor definition and RawValue property of the Valueproviderresult type in code 1-4, and then look at the code definition for the GetValue () method in code 1-3, at a glance.

4. Custom value provider Factory definition

To cut back to the main process, while we're using the custom value provider in the model binder, let's recall that the last space is about the origin of the custom value provider, which is generated by our custom value provider factory, The factory is then registered to the valueproviderfactories of the system. Factories, and then the Modelbindingcontext type instance is generated from Valueproviderfactories before the model binder executes. Factories gets the custom value provider (Mycustomvalueprovider type) assigned to the attribute Valueprovider of the Modelbindingcontext type instance (for the procedure here you can view the previous article).

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

Code 1-5

usingSYSTEM.WEB.MVC;namespacemvcapplication.valueprovider{ Public classMycustomvalueproviderfactory:valueproviderfactory { Public Overrideivalueprovider Getvalueprovider (ControllerContext controllercontext) {if(ControllerContext.Controller.GetType (). Name = ="Valueprovidercasecontroller")            {                return NewMycustomvalueprovider (); }            return NULL; }    }}

The Getvalueprovider () method in code 1-5 was added to the logic that I wanted to instruct the factory to serve only the Valueprovidercasecontroller controller, and it is not a good idea to say much about it.

5. Customizing the Model binder

Back to the main process, which says to look at the Model Binder Execution section, now look at the model binder to get some of the process. Not much to say directly to the definition of the custom model binder, code 1-6.

Code 1-6

namespace mvcapplication.binders{    publicclass  Valueprovidermodelbinder:imodelbinder    {        publicobject  Bindmodel (ControllerContext controllercontext, Modelbindingcontext BindingContext)        {            return  BindingContext.ValueProvider.GetValue (Bindingcontext.modelname). RawValue;         }}}

In code 1-6, the Valueprovider property in BindingContext has a reference to the value provider, invokes the GetValue () method in code 1-3, and passes the parameter name past for logical judgment. Finally, the value that we define is returned directly by RawValue of the return value Valueproviderresult type.

6. Register our Custom "mess" type in the MVC framework

These types of definitions are not enough, we also need to register them in the system, Convention we add in the Global.asax file, of course, can also be registered in the process of controller activation, specific controller for specific model binders, of course, in the actual project development practical not practical is not clear, just so feel Global.asax file will be "clean" Point No more nonsense, come to see the registered code definition 1-7.

Code 1-7

ModelBinders.Binders.Add (typeof(stringnew  Binders.valueprovidermodelbinder ()); ValueProviderFactories.Factories.Insert (0new valueprovider.mycustomvalueproviderfactory ( ));

Adding code 1-7 to the Application_Start () method is to first register our custom model binder with the system and then add the custom value provider factory to the system, which is added using the Insert () method. The goal is to let my factory in the default before the first position, the province again to judge a waste of time. You can also use the Add () method, except that it is added to the tail.

Finally, let's look at the result graph:

Figure 2


Jinyuan

Source: http://blog.csdn.net/jinyuan0829

This article is copyrighted by the author and Csdn, welcome reprint, but without the consent of the author must retain this statement, and on the article page

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.