"ASP 4 Real Combat" Learning Note 11: Model Binder and value provider

Source: Internet
Author: User

First, create a custom model binder:

The process of modeling a model object with request data and passing an object to an action parameter is called model binding.

Most of the time the action parameter is the primary key or other unique identifier of the object, so we do not have to place a duplicate data access code in all the actions (the "\\Before" section of the code below), but instead use a custom model binder (the "\\After" section of the code below). It can load the storage object before the action executes, so the action no longer has a unique identifier but a persisted object type as a parameter.

Beforepublic ViewResult Edit (Guid id) {  var profile=_profilerepository.getbyid (id);  Return View (new Profileeditmodel);    } Afterpublic ViewResult Edit (profile ID) {  return View (new Profileeditmodel (ID));   }

The extensibility of MVC allows us to register the model binder, which is achieved by specifying the binder that should be used for a model type. But in the case of many entities, it is desirable that we only register a custom model binder for a common base type (Common base types) or let each custom binder decide for itself whether it should be bound. To achieve this, we need to provide both a custom model binder provider and a custom model binder. The provider is used by the MVC framework to determine which model binder to use for model binding.

In order to implement a custom model binder provider, we need to implement the Imodelbinderprovider interface:

public interface imodelbinderprovider{  imodelbinder getbinder (Type modeltype)  }

Any implementation of the Imodelbinderprovider that wants to use custom matching logic only needs to detect the type of model passed in and determine if a custom model binder instance can be returned.

An implementation of the custom model binder provider:

public class entitymodelbinderprovider:imodelbinderprovider{Public    imodelbinder getbinder (Type modeltype)    {        if (!typeof (Entity). Isassignable (Modeltype))            return null;        return new Entitymodelbinder ();}    }

In the previous example, we first check whether the Modeltype parameter inherits from entity, and if not, returns Null to indicate that the model binder provider cannot provide a model binder for this given type, and instead returns a new instance of the Entitymodelbinder (Entity model Binder).

The complete model binder needs to implement the Imodelbinder interface:

 public class Entitymodelbinder:imodelbinder{public object Bindmodel (Control            Lercontext ControllerContext, Modelbindercontext bindingcontext) {Valueproviderresult value= Bindingcontext.valueprovider.                        GetValue (Bindingcontext.modelname);            if (value==null) return null; if (string. IsNullOrEmpty (value.            Attemptedvalue)) return null;            int EntityId; if (!int. TryParse (value.            Attemptedvalue,out EntityId)) {return null; } Type repositorytype=typeof (irepository<>).            MakeGenericType (Bindingcontext.modeltype); var repository= (irepository) servicelocator.            Resolve (Repositorytype); Entity entity=repository.            GetById (EntityId);    return entity; }}        
public interface irepository<tentity>    where tentity:entity{    TEntity Get (int id);}

To register a custom model binder provider:

protected void Application_Start () {    modelbinderproviders.binderproviders    . ADD (New Entitymodelbinderprovider ());}

Second, use a custom value provider:
By creating an additional custom value provider we can further eliminate the query code in the controller's action:

Beforepublic ViewResult Logonwidget (Logonwidgetmodel model) {    bool inauthenticated=request.isauthenticated;    Model. isauthenticated=isauthenticated;    Model. Currentuser=session[""];    return View (model);} Afterpublic ViewResult Logonwidget (Logonwidgetmodel model) {    bool inauthenticated=request.isauthenticated;    Model. isauthenticated=isauthenticated;    return View (model);}    

I feel that I would like to skip it, do not understand ...

"ASP 4 Real Combat" Learning Note 11: Model Binder and value provider

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.