ASP.NET MVC - 混合自定义和默认模型绑定
我有一个类型:
public class IssueForm
{
Order Order {get; set;}
Item Item {get; set;}
Range Range {get; set;}
}
由于订单和项目的要求,我创建了一个自定义模型绑定器,但范围仍然可以使用默认模型绑定器。
有没有办法从我的自定义模型绑定程序中调用默认模型绑定程序以返回 Range 对象? 我想我只需要正确设置 ModelBindingContext,但我不知道如何设置。
编辑
查看第一个评论和答案 - 似乎从默认模型绑定程序继承可能有用。
到目前为止,为了为我的设置添加更多细节,我有:
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
}
}
这可能是一种愚蠢的方法......这是我的第一个模型活页夹。 只是指出我当前的实现。
编辑#2
因此,如果我可以像“我已经完成绑定”方法一样挂载并使用属性调用 Factory 方法,那么覆盖 BindProperty 的答案将起作用。
我想我真的应该看看 DefaultModelBinder 实现并停止愚蠢。
I have a type:
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.
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.
EDIT
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.
EDIT #2
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.
I guess I really should look at the DefaultModelBinder implementation and quit being stupid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
覆盖 DefaultModelBinder 中的 BindProperty:
override the BindProperty from the DefaultModelBinder:
尝试这样的事情:
Try something like this:
我想我会注册两种不同的自定义模型绑定器,一种用于订单,一种用于项目,并让默认模型绑定器处理 Range 和 IssueForm。
I think I would have registered two different custom model binders, one for Order and one for Item, and let the default model binder handle the Range and the IssueForm.