0

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..

Pbirkoff
  • 4,642
  • 2
  • 20
  • 18

1 Answers1

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.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928