MVC 模型绑定到接口
我创建了一个 OrderFormViewModel ,它看起来像这样,
public class OrderFormViewModel
{
public IOrderDetails { get; set; }
public IDeliveryDetails { get; set; }
public IPaymentDetails { get; set; }
// ... etc
public SelectList DropDownOptions { get; set; }
// ... etc
}
这将转到我的 Create 视图,其中每个部分(即交货详细信息、付款详细信息...等)都会传递到捕获必要字段的部分视图。
我认为这一切都非常简洁,直到我运行它并意识到 MVC 模型绑定器不知道如何实例化任何接口。
有没有办法以某种方式解决这个问题?
我还尝试使用 Unity 容器学习 DI,因此我尝试避免引用 UI 项目中的任何具体类(模型位于单独的项目中)。
I have created an OrderFormViewModel which looks something like
public class OrderFormViewModel
{
public IOrderDetails { get; set; }
public IDeliveryDetails { get; set; }
public IPaymentDetails { get; set; }
// ... etc
public SelectList DropDownOptions { get; set; }
// ... etc
}
This goes to my Create view, where each section (i.e. delivery details, payment details... etc) is then passed to a partial view which captures the necessary fields.
I thought this was all quite neat until I ran it and realized of course that the MVC model binder doesn't know how to instantiate any of the interfaces.
Is there a way to resolve this somehow?
I'm also trying to learn DI using the Unity container, so I'm trying to avoid having references to any concrete classes in my UI project (model is in a separate project).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种解决方案是创建自定义模型绑定程序,但此方法意味着您需要将表单元素转换为对象的属性。但是,例如,您可以完全控制使用 IOrderDetails 的实现,或者您可以让 DI 使用其配置为您提供正确的具体类型。
One solution is to make a custom model binder, but this path means you will need to go through the effort of translating form elements to properties on your object. However, you have complete control over which implementation of IOrderDetails gets used, for example, or you can have your DI give you the right concrete type using it's configuration.
可能的解决方案可能在这里(在接口绑定过滤器与视图模型绑定下):
http://codetunnel.com/aspnet-mvc-model-binding-security/
A possible solution might be here (under Interface Binding Filter vs View Model Binding):
http://codetunnel.com/aspnet-mvc-model-binding-security/