ASP. NET MVC Model binding (III)

Source: Internet
Author: User

ASP. NET MVC Model binding (III) Preface

The first two friends must have a general understanding of the model binding, however, the MVC framework provides us with a higher scalability of the provider programming model, which is the topic of this article, will explain the model binder provider Implementation and solve the previous issue left.

The first question is the modelbinderprovidercollection type of execution process?

Another issue in this article is the same as registering the model binder and the model binder provider in the system context, which has a higher priority?

Model binding
    • Imodelbinder , custom model Simple implementation of the binder
    • Model Binder in MVC position in the frame
    • MVC the default model in Binder Generation Process
    • Imodelbinderprovider the simple application
    • Ivalueprovider in MVC the positions and procedures generated in the framework
    • Ivalueprovider the application Scenario
    • Ivalueprovider the realization of the Namevaluecollectionvalueprovider

Simple application of Imodelbinderprovider

First, let's take a look at the definition of the Imodelbinderprovider type, code 1-1:.

Code 1-1

     Public InterfaceImodelbinderprovider {//Summary://returns the model binder for the specified type. //        //Parameters://Modeltype://the type of the model. //        //return Result://the model binder for the specified type. imodelbinder Getbinder (Type modeltype); }

In code 1-1, we see that the Getbinder () method does something based on the type of ViewModel, and finally returns the model binder. Now we customize the implementation of a model binder provider code 1-2.

Code 1-2

usingSYSTEM.WEB.MVC;usingConsoleApplication2;namespacemvcapplication.infrastructure{ Public classMycustommodelbinderprovider:imodelbinderprovider { Publicimodelbinder Getbinder (Type modeltype) {if(Modeltype = =NULL)            {                Throw NewArgumentNullException ("Modeltype"); }            if(Modeltype = =typeof(Customer)) {               //returns the model binder corresponding to the customer type            }            return NULL; }    }}

In code 1-2 we determine whether the customer type is based on Modeltype, and then return the model binder that corresponds to the customer type. Why the implementation here is empty, because I want to use the IOC framework we've explained earlier, let the model binder provider decoupled from the model binder, and want to define the application of the IOC framework in the context of the current system, let's take a look at the code implementation, code 1-3.

Code 1-3

usingSYSTEM.WEB.MVC;usingNinject;usingSystem.ComponentModel;usingSystem.ComponentModel.Design;usingMvcApplication.Infrastructure.NinjectControllerPart;namespacemvcapplication{ Public classMvcsystemcontext {Private StaticMvcsystemcontext _mvcsystemcontext;  Public Staticmvcsystemcontext Context {Get            {                if(_mvcsystemcontext = =NULL) {_mvcsystemcontext=NewMvcsystemcontext (); }                return_mvcsystemcontext; }        }        PrivateServiceContainer _servicecontainer; PrivateMvcsystemcontext () {_servicecontainer=NewServiceContainer (); _servicecontainer.addservice (typeof(Ninjectcontroller), ninjectcontroller.instance); }         PublicNinjectcontroller Ninjectcontroller {Get            {                return(Ninjectcontroller) _servicecontainer.getservice (typeof(Ninjectcontroller)); }        }    }}

In code 1-3, I define the current system context, but this is for yourself, the context object must not be used to all the data or functions are added to the inside, just add a reference, such as code 1-3 in the Ninjectcontroller property, The type that corresponds to the Ninjectcontroller property is the Ninjectcontroller type, and the function of the Ninjectcontroller type is to provide the functionality of the IOC framework Let's take a look at the definition for the Ninjectcontroller type in code 1-4.

Code 1-4

usingNinject;namespacemvcapplication.infrastructure.ninjectcontrollerpart{ Public classNinjectcontroller {Private StaticNinjectcontroller _instance;  Public StaticNinjectcontroller Instance {Get             {                return_instance =NewNinjectcontroller (); }        }        PrivateIkernel _ninjectkernel; PrivateNinjectcontroller () {_ninjectkernel=NewStandardkernel (); }         Public voidAddkernelbind<t, U> ()whereu:t {_ninjectkernel.bind<T> (). To<u>(); }         PublicT getvaluetype<t>(Type keyType) {varValueType =_ninjectkernel.get (KeyType); return(T) ValueType; }    }}

Which for Ninject this IOC framework has a most basic function encapsulation, some friends may ask why not public a property, why so superfluous, because I am not very skilled in the use of ninject, for this part of the package I just let its simple public two features, One is to bind one is to get the value, so that this part of the content is still within my control, if it is the public property, other people's indiscriminate use caused by the wrong words is not controllable.

Cut back to the theme so that after the basic definition, we then modify the code in 1-2, the specific implementation to add, example code 1-5 is shown.

Code 1-5

if typeof (Customer)) {    // return model binder    for customer type return Mvcsystemcontext.context.ninjectcontroller.getvaluetype<imodelbinder> (typeof(IModelBinder) );}

As you can see in code 1-5, given the IOC capabilities provided in our custom context to get the values bound in the IOC framework, where is the binding? As shown in the ASP. NET MVC Model binding (a), it is also added as code 1-6 in the Application_Start () method of the Mvcapplication type in the project's Global.asax file.

Code 1-6

Mvcsystemcontext.context.ninjectcontroller.addkernelbind<imodelbinder, binders.mycustommodelbinder>() ; MODELBINDERPROVIDERS.BINDERPROVIDERS.ADD (new Mycustommodelbinderprovider ());

Code 1-6 did two operations, first registering the model binder corresponding to the customer type in the IOC of our custom context, and then registering the model binder provider for processing the customer type into the system. Run result 1.

Figure 1

The code that covers all parts is the same as the ASP. NET MVC Model binding (a), so this is not listed here.

As shown in the last figure 2 in the previous article, we can tell that the execution of the modelbinderprovidercollection type is based on the current parameterdescriptor The model type provided by the type is compared to the model binder provider collection that we have registered to or is provided by default, if there is a model type provided for the parameterdescriptor type (in the example above Customer type), the model binder is returned and then the model binding is based on the model binder.

Okay, now the first problem is solved, to solve the second problem. See Code 1-7 below.

Code 1-7

     Public classMycustommodelbinder:imodelbinder { Public ObjectBindmodel (ControllerContext controllercontext, Modelbindingcontext bindingcontext) {return NewCustomer () {CustomerID="010", Name="Test Personnel", Registrationdate=DateTime.Now, Address=NewAddress () {addressname="the city of the Sky"                }            }; }    }     Public classMycustommodelbinder_test:imodelbinder { Public ObjectBindmodel (ControllerContext controllercontext, Modelbindingcontext bindingcontext) {return NewCustomer () {CustomerID="010", Name="Test Personnel", Registrationdate=DateTime.Now, Address=NewAddress () {addressname="This is the model that is executed according to the model binder binding"                }            }; }    }

See the Mycustommodelbinder_test type in code 1-7 internal the Addressname value inside the customer type instance has changed and is not the same as before. Take a look at the registration side of the changes, example code 1-8.

Code 1-8

ModelBinders.Binders.Add (typeofnew  binders.mycustommodelbinder_test ()); MVCSystemContext.Context.NinjectController.AddKernelBind<imodelbinder, binders.mycustommodelbinder> (); MODELBINDERPROVIDERS.BINDERPROVIDERS.ADD (new Mycustommodelbinderprovider ());

In code 1-8, we register the newly defined mycustommodelbinder_test type in the system's model binder collection to see which level is higher.

See Running results Figure 2

Figure 2

See Figure 2 For this result, presumably already know which level is higher.

Jinyuan

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

This article is copyrighted by the author and the blog Park, 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.