Pol*_*878 10 asp.net-mvc model-binding
好吧,假设我有一个像这样的URL,它通过HTTP动词映射GET
到我在下面的控制器操作:
GET /foo/bar?sort=asc&r=true
Run Code Online (Sandbox Code Playgroud)
如何Bar
在我的控制器操作上将其绑定到我的模型,我在下面:
class Bar {
string SortOrder { get; set; }
bool Random { get; set; }
}
public ActionResult FooBar(Bar bar) {
// Do something with bar
return null;
}
Run Code Online (Sandbox Code Playgroud)
请注意,属性名称不会也不一定与URL参数的名称匹配.此外,这些是可选的url参数.
Max*_*oro 12
它不支持开箱即用,但您可以这样做:
class BarQuery : Bar {
public string sort { get { return SortOrder; } set { SortOrder = value; } }
public bool r { get { return Random; } set { Random = value; } }
}
public ActionResult FooBar(BarQuery bar) {
// Do something with bar
}
Run Code Online (Sandbox Code Playgroud)
您可以实现自定义IModelBinder
,但手动映射更容易.
class FromQueryAttribute : CustomModelBinderAttribute, IModelBinder {
public string Name { get; set; }
public FromQueryAttribute() { }
public FromQueryAttribute(string name) {
this.Name = name;
}
public override IModelBinder GetModelBinder() {
return this;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
return controllerContext.HttpContext.QueryString[this.Name ?? bindingContext.ModelName];
}
}
class Bar {
[FromQuery("sort")]
string SortOrder { get; set; }
[FromQuery("r")]
bool Random { get; set; }
}
public ActionResult FooBar(Bar bar) {
// Do something with bar
return null;
}
Run Code Online (Sandbox Code Playgroud)
模型绑定器将它从视图获取的参数与名称中操作中的模型匹配,因此如果它们不匹配,则绑定将不起作用.
你有的选择:
所以基本上,你不能做你想要的.
更新:
您在评论中写道,属性可以与参数名称匹配,因此不要编写可能成功进行绑定的自定义属性,只需编写ViewModel(VM fromMVC ...)来调整url参数名称.
MVC团队不建议编写自定义模型绑定器:
在一般情况下,我们建议人们不要写自定义模型粘合剂,因为他们难以得到的权利和他们很少需要
从这里