ASP. net mvc Model binding (3)

Source: Internet
Author: User

ASP. net mvc Model binding (3)Preface

Those who have read the first two articles may have a rough understanding of Model binding. However, the MVC Framework provides us with a higher scalability programming mode, which is the topic of this article, it will explain the implementation of the Model binder provider and solve the problems left over from the previous article.

The first question is: how to execute the ModelBinderProviderCollection type?

Another question in this article is to register the Model binder and the Model binder provider in the system context. Which one has a higher priority?

 

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

 

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 {// Abstract: // return the model concatenation program of the specified type. //// Parameter: // modelType: // model type. //// Return result: // model concatenation program of the specified type. IModelBinder GetBinder (Type modelType );}

In code 1-1, we can see that the GetBinder () method is to perform some operations based on the ViewModel type, and finally return the Model binder. Now we customize the implementation of a Model binder provider with 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) {// return the Model binder of the corresponding Customer type} return null ;}}}

In code 1-2, we determine whether the Model type is the Customer type based on modelType, and then return the Model binder of the corresponding Customer type. Why is the implementation empty here, because I want to use the IoC framework we have explained earlier, so that the Model binder provider can be unbound from the Model binder, 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

using System.Web.Mvc;using Ninject;using System.ComponentModel;using System.ComponentModel.Design;using MvcApplication.Infrastructure.NinjectControllerPart;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));            }        }    }}

Code 1-3 is the current system context defined by me, but this is for your own use. The context object will not add all the data or functions used in it, just add a reference. For example, in code 1-3, the NinjectController attribute corresponds to the NinjectController type. The NinjectController type is used to provide the IoC framework function, let's take a look at the definition of 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;        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;        }    }}

The Ninject IoC framework is encapsulated with the most basic functions. Some may ask why an attribute is not published, because I am not very familiar with Ninject, I just made two simple functions public for this encapsulation. One is to bind one is to get the value, in this way, this part of content is still within my controllable scope. If it is a public attribute, other people's usage will lead to errors, which will be uncontrollable.

Switch back to the topic. After the basic definition is completed, we can modify the code in 1-2 to add the specific implementation, as shown in the example code 1-5.

Code 1-5

If (modelType = typeof (Customer) {// return the return MVCSystemContext. Context. NinjectController. GetValueType <IModelBinder> (typeof (IModelBinder ));}

In code 1-5, we can see that the IoC function provided in the Custom context gets the value bound to the IoC framework. Where is the binding? As demonstrated by binding with ASP. net mvc Model (1), add code 1-6 in the MvcApplication Application_Start () method 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 performs two Operations respectively. First, the Model binder corresponding to the Customer type is registered to the IoC of the custom context, then, register the Model binder provider that processes the Customer type to the system. Result 1.

Figure 1

The code that involves all parts is the same as that in ASP. net mvc Model binding (1), so it is not listed here.

Based on the steps shown in Figure 2 at the end of the previous article, we can determine that the execution process of the ModelBinderProviderCollection type is based on the currentParameterDescriptorCompared with the Model type provided by the Model type, we have registered it or the set of Model bindings provided by the system by default.ParameterDescriptorThe Model type provided by the type (in the above exampleCustomerType.

 

Now the first problem has been solved to solve the second problem. See Code 1-7.

Code 1-7

Public class MyCustomModelBinder: IModelBinder {public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {return new Customer () {CustomerID = "010", Name = "tester", RegistrationDate = DateTime. now, Address = new Address () {AddressName = "City of the Sky" };}} public class MyCustomModelBinder_Test: IModelBinder {public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {return new Customer () {CustomerID = "010", Name = "tester", RegistrationDate = DateTime. now, Address = new Address () {AddressName = "here is the Model executed by binding the Model binder "}};}}

We can see that the AddressName value in the MyCustomModelBinder_Test instance of the Customer type in code 1-7 has been changed and is different from the previous one. Let's take a look at the registration end's changes. The sample code is 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 registered the newly defined MyCustomModelBinder_Test type to the system's Model binder set to see which level is higher.

Figure 2

Figure 2

When you see the result in Figure 2, you must know which level is higher.

 

 

 

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.