0

I'm following this example to the exact with a minor change in my ViewModel

public abstract class BaseViewModel
{
    public int Id { get; set; }
}

public class FooViewModel : BaseViewModel
{
    public string Foo { get; set; }
    public IEnumerable<string> Options { get; set; }
}

How to make the IEnumerable property in the above example work?

Community
  • 1
  • 1
maztt
  • 12,278
  • 21
  • 78
  • 153

1 Answers1

0

Based on the title, I'm assuming your question is how to post Options when your action accepts only BaseViewModel, i.e.:

public ActionResult Foo(BaseViewModel model)
{
    // do something with `model.Options`
}

If that's the case, the answer is you can't. The result of a post is just a collection of key-value pair strings. The modelbinder is tasked with taking this data and transforming it into the parameter(s) your action accepts, instantiating classes and setting properties as appropriate. However, it's not psychic. It needs guidance in the form of your action parameter types. Given that, based on the action, it's going to instantiate BaseViewModel and then see which properties on that it can fill. It will fill Id, but then it's done. It will simply discard the rest of the posted data, because there's nothing more it can do on BaseViewModel. The modelbinder has no way of knowing that FooViewModel is actually what you want. If you need an instance of FooViewModel, then you must type your action parameter as that. Nothing else will work.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444