ASP.NET MVC - 混合自定义和默认模型绑定 [英] ASP.NET MVC - Mixing Custom and Default Model Binding
问题描述
我有一个类型:
public class IssueForm
{
Order Order {get; set;}
Item Item {get; set;}
Range Range {get; set;}
}
我创建了一个自定义的模型绑定由于对订单和项目要求,但仍范围可以使用默认的模型绑定。
I created a custom model binder due to requirements on Order and Item, but Range could still use the Default Model Binder.
有没有从我的自定义模型粘合剂中的方式来调用默认的模型绑定返回一个Range对象?我想我只需要设置只是正确ModelBindingContext,但我不知道怎么办。
Is there a way from within my custom model binder to call the default model binder to return a Range object? I think I just have to just setup ModelBindingContext correctly, but I don't know how.
修改
看一下第一个注释和答案 - 这似乎是从默认的模型绑定继承可能是有用的。
Looking at the first comment and answer -- it seems like inheriting from the default model binder could be useful.
要为我的设置添加更多的细节到目前为止,我有:
To add more specifics for my setup so far I have:
public IssueFormModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Order = //code to pull the OrderNumber from the context and create an Order
Item = //code to pull the ItemNumber from the context and create an Item
IssueForm form = IssueFormFactory.Create(Order, Item);
form.Range = // ** I'd like to replace my code with a call to the default binder **
return form
}
}
这可能是做这件事的一个笨方法......这是我的第一个模型粘合剂。只是指出我目前的执行情况。
This might be a stupid way of doing it... this is my first model binder. Just pointing out my current implementation.
编辑#2
所以答案覆盖BindProperty将工作,如果我可以挂接到像我都做结合的方法,并调用工厂方法与属性。
So the answers to override BindProperty will work if I can hook into like a "I'm all done binding" method and call the Factory method with the properties.
我想我真的应该看看DefaultModelBinder执行和退出太傻了。
I guess I really should look at the DefaultModelBinder implementation and quit being stupid.
推荐答案
尝试是这样的:
public class CustomModelBinder : DefaultModelBinder {
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) {
if(propertyDescriptor.Name == "Order") {
...
return;
}
if(propertyDescriptor.Name == "Item") {
...
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
这篇关于ASP.NET MVC - 混合自定义和默认模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!