MVC 3 中的模型绑定接口数组
我正在寻找一种方法来在 MVC 3 中实现以下目标。
假设我有一个页面有一个问题。在一篇文章中,我想绑定以下 ViewModel:
public class QuestionElementViewModel
{
public int QuestionId { get; set; }
public string Name { get ; set; }
public string Question { get; set; }
public string Feedback { get; set; }
}
这可以很容易地完成,如下所示(如果我在视图中使用正确的名称):
[HttpPost]
public ActionResult Index(QuestionElementViewModel pm)
{
//Do something
}
现在我的页面上有多个问题。使用此处解释的技术: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx 我也可以让这变得很简单:
[HttpPost]
public ActionResult Index(QuestionElementViewModel[] pm)
{
//Do Something
}
但是可以说我不仅有问题,而且有不同的问题我的页面上的元素,并且这些元素可能会有所不同。是否有可能实现这样的目标:
[HttpPost]
public ActionResult Index(IElementViewModel[] pm)
{
//Do Something
}
每个实现此接口的 ViewModel 都会自动绑定?
我已经尝试过这段代码,但它会导致错误:无法创建接口实例,这听起来很明显。
我认为我应该创建一个自定义模型绑定器,但我对此不太熟悉,而且我不想太多地脱离标准 MVC 框架。
I'm looking for a way to achieve the following in MVC 3.
Let's say I have a page with one question. On a post, I would like to bind the following ViewModel:
public class QuestionElementViewModel
{
public int QuestionId { get; set; }
public string Name { get ; set; }
public string Question { get; set; }
public string Feedback { get; set; }
}
This can easily be done like this (if I use the correct names in the View):
[HttpPost]
public ActionResult Index(QuestionElementViewModel pm)
{
//Do something
}
Now I have multiple questions on my page. Using the technique explained here: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx I can also make this quite easy:
[HttpPost]
public ActionResult Index(QuestionElementViewModel[] pm)
{
//Do Something
}
But lets say I don't have only questions, but different elements on my page and these elements can vary. Would it be somehow possible to achieve something like this:
[HttpPost]
public ActionResult Index(IElementViewModel[] pm)
{
//Do Something
}
where every ViewModel that implements this interface is automatically bound?
I've tried this code and it results in an error: Cannot create instance of an interface, which sounds pretty obvious.
I think i should create a custom model-binder, but I'm not very familiar with that and I don't want to step away from the standard MVC-framework too much..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于这种情况,您将需要一个自定义模型绑定器,因为您正在使用接口,并且默认模型绑定器不知道要实例化哪个实现。因此,一种可能的技术是使用包含每个元素的具体类型的隐藏字段。这是一个示例,可能会让您走上正轨。
You will need a custom model binder for this scenario because you are using an interface and the default model binder wouldn't know which implementation to instantiate. So one possible technique is to use a hidden field containing the concrete type for each element. Here's an example that might put you on the right track.