Method parameter with (attribute) in brackets

筅森魡賤 提交于 2019-12-01 10:36:46

What you are seeing is a model binder attribute. The DataSourceRequest is actually DataSourceRequestAttribute and extends the CustomModelBinderAttribute class. Creating such an attribute is fairly simple:

First we need a model:

public class MyModel
{
    public string MyProp1 { get; set; }

    public string MyProp2 { get; set; }
}

We need to be able to create the binding, by creating a custom model binder. Depending on how your values are sent to the server, get the values either from the form or the query string:

public class MyModelBinder : IModelBinder
{
     public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext)
     {
         MyModel model = new MyModel();

         //model.MyProp1 = controllerContext.HttpContext.Request.Form["MyProp1"];
         //model.MyProp2 = controllerContext.HttpContext.Request.Form["MyProp2"];
         //or
         model.MyProp1 = controllerContext.HttpContext.Request.QueryString["MyProp1"];
         model.MyProp2 = controllerContext.HttpContext.Request.QueryString["MyProp2"];

         return model;
     }
}

The last thing we need to do is create the model binder attribute which can be set inside the action result signature. Its sole purpose is specifying the model binder which must be used for the parameter it decorates:

public class MyModelBinderAttribute : CustomModelBinderAttribute
{
     public override IModelBinder GetBinder()
     {
          return new MyModelBinder();
     }
}

The custom binding can be tested by creating a simple ActionResult and calling it with the parameters in the query string (since my implementation above looks for parameters in the query string):

public ActionResult DoBinding([MyModelBinder]MyModel myModel)
{
    return new EmptyResult();
}

//inside the view
<a href="/Home/DoBinding?MyProp1=value1&MyProp2=value2">Click to test</a>

As DavidG noted, the DataSourceRequestAttribute is different than DataSourceRequest. They appear to have the same names due to the Attribute name convention, i.e. DataSourceRequestAttribute looses the Attribute part when decorating an object or a property.

As a conclusion, the DataSourceRequestAttribute just tells the framework that a custom model binder (probably DataSourceRequestModelBinder or something similar) should be used for the DataSourceRequest request parameter.

Please see the following links for additional information: source, source.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!