括号中带有(attribute)的方法参数

我有一个来自KendoUI的代码示例。

public ActionResult Customers_Read([DataSourceRequest]DataSourceRequest request) { return Json(GetCustomers().ToDataSourceResult(request)); } private static IEnumerable GetCustomers() { var northwind = new SampleEntities(); return northwind.Customers.Select( customer => new CustomerViewModel { CustomerID = customer.CustomerID, CompanyName = customer.CompanyName, ContactName = customer.ContactName, ... }); } 

这个例子工作正常。

我对Customers_Read方法中的[DataSourceRequest]感到困惑…

当我删除(?属性?) [DataSourceRequest] ,请求的属性为空(null)…(它们没有绑定) – >结果:filter不起作用..

什么是[DataSourceRequest] ? 这就像属性属性?

代码示例 – > IndexController.cs代码示例

您所看到的是模型绑定器属性。 DataSourceRequest实际上是DataSourceRequestAttribute并扩展了CustomModelBinderAttribute类。 创建这样的属性非常简单:

首先我们需要一个模型:

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

我们需要能够通过创建自定义模型绑定器来创建绑定。 根据您的值发送到服务器的方式,从表单或查询字符串中获取值:

 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; } } 

我们需要做的最后一件事是创建模型绑定器属性,该属性可以在操作结果签名中设置。 它的唯一目的是指定模型绑定器,它必须用于它装饰的参数:

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

可以通过创建一个简单的ActionResult并使用查询字符串中的参数调用它来测试自定义绑定(因为我的上面的实现在查询字符串中查找参数):

 public ActionResult DoBinding([MyModelBinder]MyModel myModel) { return new EmptyResult(); } //inside the view Click to test 

正如DavidG所指出的, DataSourceRequestAttributeDataSourceRequestAttribute不同。 由于Attribute名称约定,它们似乎具有相同的名称,即DataSourceRequestAttribute在装饰对象或Attribute时会丢失Attribute部分。

作为结论, DataSourceRequestAttribute只是告诉框架应该为DataSourceRequest request参数使用自定义模型绑定器(可能是DataSourceRequestModelBinder或类似的东西)。

有关其他信息,请参阅以下链接: 来源 , 来源 。