为属性自定义模型绑定 [英] Custom model binder for a property
问题描述
我有以下控制器动作:
[HttpPost]
公众的ViewResult DoSomething的(为MyModel模型)
{
// 做一点事
返回查看();
}
为MyModel看起来是这样的:
公共类为MyModel
{
公共字符串PropertyA {搞定;组;}
公众的IList< INT> PropertyB {搞定;组;}
}
所以DefaultModelBinder应该绑定这个没有问题。唯一的一点是,我要使用特殊/定制绑定绑定PropertyB,我也想重用这个粘合剂。因此,我认为,解决办法是PropertyB这当然不工作之前,把一个ModelBinder的属性(属性ModelBinder的上不允许一个属性)。我看到两种解决方案:
1)用行动参数,而不是模型,我不知道preFER(模型有很多属性...)这样的:
公开的ViewResult DoSomething的(字符串propertyA,[ModelBinder的(typeof运算(MyModelBinder))] propertyB)...
2)要创建一个新的类型可以说MyCustomType:列表和注册模型绑定对于这种类型的(这是一个选项)
是否有任何其他第三方的解决方案?也许创建为MyModel粘合剂,覆盖BindProperty如果属性为PropertyB绑定我的定制绑定属性。这可能吗?
谢谢您的回答...
覆盖BindProperty如果
属性为PropertyB绑定
我的定制绑定属性
块引用>这是一个很好的解决方案,但不是检查是PropertyB你最好检查定义属性级别的粘合剂,像
自己的自定义属性[PropertyBinder(typeof运算(PropertyBBinder))]
公众的IList&LT; INT&GT; PropertyB {搞定;组;}您可以看到BindProperty覆盖的<一个例子href=\"http://stackoverflow.com/questions/970335/asp-net-mvc-mixing-custom-and-default-model-binding\">here.
I have a following controller action:
[HttpPost] public ViewResult DoSomething(MyModel model) { // do something return View(); }
MyModel looks like this:
public class MyModel { public string PropertyA {get; set;} public IList<int> PropertyB {get; set;} }
So DefaultModelBinder should bind this without a problem. The only thing is that I want to use special/custom binder for binding PropertyB and I also want to reuse this binder. So I thought that solution would be to put a ModelBinder attribute before the PropertyB which of course doesn't work (ModelBinder attribute is not allowed on a properties). I see two solutions:
1.) To use action parameters instead of model which I don't prefer (the model has a lot of properties...) like this:
public ViewResult DoSomething(string propertyA, [ModelBinder(typeof(MyModelBinder))] propertyB) ...
2.) To create a new type lets say MyCustomType: List and register model binder for this type (this is an option)
Is there any other, third solution? Maybe to create a binder for MyModel, override BindProperty and if the property is "PropertyB" bind the property with my custom binder. Is this possible?
Thanks for your answers...
解决方案override BindProperty and if the property is "PropertyB" bind the property with my custom binder
That's a good solution, though instead of checking "is PropertyB" you better check for your own custom attributes that define property-level binders, like
[PropertyBinder(typeof(PropertyBBinder))] public IList<int> PropertyB {get; set;}
You can see an example of BindProperty override here.
这篇关于为属性自定义模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!