MVC source code analysis, mvc source code

Source: Internet
Author: User

MVC source code analysis, mvc source code

I have never felt wrong over the past few days. I always thought I was missing something. Today I found out that3When obtaining the parameter information of the Action, it is not parsed. There is another important thing in it. The same is true today.

In the InvokeAction () method, there is a code:

IDictionary<string, object> parameterValues = this.GetParameterValues(controllerContext, actionDescriptor);

This is used to obtain parameters. Do you want to obtain the parameters at will? In Mvc, when the page transmits parameters to the Action, have you ever tried to upload an array and parse it into an array when receiving the parameter? Or receive more complex types?

The answer is in this article. Let's look at the source code first.

protected virtual IDictionary<string, object> GetParameterValues(ControllerContext controllerContext,
   ActionDescriptor actionDescriptor){ Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); foreach (ParameterDescriptor descriptor in actionDescriptor.GetParameters()) { dictionary[descriptor.ParameterName] = this.GetParameterValue(controllerContext, descriptor); } return dictionary;}

I. source code parsing

1. actionDescriptor. GetParameters ()

//System.Web.Mvc.ReflectedActionDescriptorpublic override ParameterDescriptor[] GetParameters(){    return ActionDescriptorHelper.GetParameters(this, this.MethodInfo, ref this._parametersCache);}

All parameters and their descriptions should be obtained here.

 

2. this. GetParameterValue () -- main method

Protected virtual object GetParameterValue (ControllerContext controllerContext,
ParameterDescriptor parameterDescriptor) {Type parameterType = parameterDescriptor. ParameterType;
// IModelBinder modelBinder = this. GetModelBinder (parameterDescriptor); IValueProvider valueProvider = controllerContext. Controller. ValueProvider; string str = parameterDescriptor. BindingInfo. Prefix ?? ParameterDescriptor. ParameterName;
// Obtain the filter above the parameter and put it in the parameter resolution context (ModelBindingContext) Predicate <string> propertyFilter = GetPropertyFilter (parameterDescriptor) below ); modelBindingContext bindingContext = new ModelBindingContext {FallbackToEmptyPrefix = parameterDescriptor. bindingInfo. prefix = null, ModelMetadata = ModelMetadataProviders. current. getMetadataForType (null, parameterType), ModelName = str, ModelState = controllerContext. controller. viewData. modelState, PropertyFilter = propertyFilter, ValueProvider = valueProvider };
// Return (modelBinder. BindModel (controllerContext, bindingContext )?? ParameterDescriptor. DefaultValue );}

 

2.1 GetModelBinder () method

private IModelBinder GetModelBinder(ParameterDescriptor parameterDescriptor){    return (parameterDescriptor.BindingInfo.Binder ?? 
      this.Binders.GetBinder(parameterDescriptor.ParameterType));}

Here is the processing interface for obtaining Parameters Based on the parameter description.

public interface IModelBinder{    // Methods    object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);}

 

2.2 BindModel () method-here we see defamodelmodelbinder, which will be customized later

Public virtual object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {EnsureStackHelper. ensureStack (); if (bindingContext = null) {throw new ArgumentNullException ("bindingContext");} bool flag = false; if (! String. IsNullOrEmpty (bindingContext. ModelName)
&&! BindingContext. ValueProvider. ContainsPrefix (bindingContext. ModelName) {if (! BindingContext. fallbackToEmptyPrefix) {return null;} ModelBindingContext context = new ModelBindingContext {ModelMetadata = bindingContext. modelMetadata, ModelState = bindingContext. modelState, PropertyFilter = bindingContext. propertyFilter, ValueProvider = bindingContext. valueProvider}; bindingContext = context; flag = true;} if (! Flag) {bool flag2 = should?mrequestvalidation (controllerContext, bindingContext); bool skipValidation =! Flag2; ValueProviderResult valueProviderResult = bindingContext. UnvalidatedValueProvider
. GetValue (bindingContext. ModelName, skipValidation); if (valueProviderResult! = Null ){
// Return the parameter value return this. BindSimpleModel (controllerContext, bindingContext, valueProviderResult) for a simple object;} if (! BindingContext. ModelMetadata. IsComplexType) {return null;} return this. BindComplexModel (controllerContext, bindingContext );}

The content here is a little too much and a little complicated. In fact, after parsing it, I almost got what I want.

 

Ii. Custom ModelBinder

1. IModelBinder -- this method can be used for relatively simple types.

First, create a slightly more complex class.

Public enum GenderEnum {Female, Male, Unknow} public class ExtInfo {public string QQ {get; set;} public string Phone {get; set ;}} public class User {
// Here is the constructor. I have created an ExtInfo instance. Otherwise, the ExtInfo object will be empty and will affect my demonstration of public User () {Extension = new ExtInfo ();}
Public int Id {get; set;} public string Name {get; set;} public GenderEnum Gender {get; set;} public ExtInfo Extension {get; set ;}}

Next, let's take a look at the Controller code.

public class ModelController : Controller{    public ActionResult Get(User user)    {        return View(user);    }    public ActionResult Index([ModelBinder(typeof(ModelIndexBinder))]User user)    {        return View(user);    }}

In the controller, I have marked it red. Next, let's look at my custom ModelBinder.

public class ModelIndexBinder : IModelBinder{    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)    {        var request = controllerContext.HttpContext.Request;        User user = new User        {            Id = Convert.ToInt32(request.Params["Id"]),            Name = request.Params["Name"].ToString(),            Gender = (GenderEnum)Convert.ToInt32(request.Params["Gender"]),            Extension = new ExtInfo            {                QQ = request.Params["QQ"].ToString(),                Phone = request.Params["Phone"].ToString()            }        };        return user;    }}

Let's take a look at the effects of the two methods.

Index Get

 

 

 

Note: there are other ways to achieve the goal. You only need to modify the url:

http://localhost:11620/model/Get?id=1&name=haha&gender=0&Extension.qq=123123123&Extension.phone=12312341234

This is an example.

It is relatively simple to use IModelBinder, but for a little more complex, you can implement defamodelmodelbinder.

However, this part of implementation will not be resolved, and I have never used it for the moment.

Generally, the Url Get request is not complex, and a complicated processing method is encountered only when the Post request is used. however, for such complex processing, there is also a commonly used method, that is, the deserialization method. I often use Newtonsoft.

 

Refer:

MVC Extension

In-depth Asp.net Mvc

 

Directory synchronized

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.