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 interface imodelbinderprovider     {        //  Summary:         //      returns the model binder for the specified type.         //        //  Parameters:         //   modelType:      The type of the    //      model.         //        //  return Results :        //      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

using system.web.mvc;using consoleapplication2;namespace mvcapplication.infrastructure{     public class MyCustomModelBinderProvider : IModelBinderProvider     {        public imodelbinder getbinder ( Type modeltype)         {             if  (modeltype == null)              {                 throw new argumentnullexception ("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

namespace mvcapplication{    public class mvcsystemcontext     {        private static mvcsystemcontext _ Mvcsystemcontext;        public static mvcsystemcontext  Context        {             get            {                 if  (_ Mvcsystemcontext == null)                  {                     _mvcsystemcontext = new mvcsystemcontext ();                 }                 return _MVCSystemContext;             }        }         private ServiceContainer _serviceContainer;         private mvcsystemcontext ()         {             _servicecontainer = new servicecontainer ();             _servicecontainer.addservice (typeof ( Ninjectcontroller), ninjectcontroller.instance);        }         public NinjectController 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

using ninject;namespace mvcapplication.infrastructure.ninjectcontrollerpart{     public class ninjectcontroller    {         private static NinjectController _Instance;         public static ninjectcontroller instance        {             get              {                 return _instance = new ninjectcontroller ();             }         }        private IKernel _ninjectKernel;        &Nbsp;private ninjectcontroller ()         {             _ninjectkernel = new standardkernel ();         }        public void  AddKernelBind<T, U> () where u:t        {             _ninjectKernel.Bind<T> (). To<u> ();        }         public T GetValueType<T> (Type keytype)          {            var valueType =  _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 (Modeltype = = typeof (Customer)) {//returns the model binder that corresponds to the customer type return MVCSystemContext.Context.NinjectController.GetV Aluetype<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

650) this.width=650; "src=" Http://images.cnitblog.com/i/627988/201406/302231581527137.png "width=" 651 "height=" 223 "/>

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 class mycustommodelbinder:imodelbinder    {         public object bindmodel (controllercontext controllercontext,  Modelbindingcontext bindingcontext)         {             return new customer ()              {                 CustomerID =  "010",                 Name =  "Testers",                 registrationdate = datetime.now,                 address =  new address () &NBSP;&NBsp;              {                      addressname =  "Sky City"                  }            };         }    }    public class  mycustommodelbinder_test : imodelbinder    {         public object bindmodel (controllercontext controllercontext,  Modelbindingcontext bindingcontext)         {             return new customer ()              {                customerid  =  "010",                 name =  "Testers",                 RegistrationDate = DateTime.Now,                 address = new address ()                  {                     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. Then look at the revision of the book end, example code 1-8.

Code 1-8

ModelBinders.Binders.Add (typeof (Customer), New 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

650) this.width=650; "src=" Http://images.cnitblog.com/i/627988/201406/302233442626888.png "width=" 640 "height=" 219 "/>

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

This article is from the "Jinyuan" blog, please be sure to keep this source http://jinyuan.blog.51cto.com/8854733/1432752

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.