views:

44

answers:

1

Does ASP.NET MVC offer any simple way to get model binding to work when you have model classes that inherit from others?

In my scenario I have a View that is strongly typed to List<Person>.

I have a couple of classes that inherit from Person, namely PersonTypeOne and PersonTypeTwo.

I have three strongly typed partial views with names that match these class names (and render form elements for the properties of their respective models).

This means that in my main View I can have the following code:

<% for(int i = 0; i < Model.Count; i++)
   { 
       Html.RenderPartial(Model[i].GetType().Name, Model[i]);
   } %>

This works well, apart from when the user submits the form the relevant controller action method just gets a List<Person>, rather than a list of Person, PersonTypeOne and PersonTypeTwo.

This is pretty much as expected as the form submission doesn't contain enough information to tell the default model binder to create any instances of PersonTypeOne and PersonTypeTwo classes.

So, is there any way to get such functionality from the default model binder?

+2  A: 

You should just create separate models to bind to your input. Your ViewModels and EditModels are truly distinct responsibilities and thus deserve their own objects.

Keith Rousseau
Are you saying that the action method that receives a form POST should accept an argument of a type that is completely different to those which are used for the strongly typed views?
Richard Ev
Yes, that is absolutely what I'm saying. If you think about it, your ViewModel that is used for rendering will have dropdown lookup values, possibly text that is formatted specifically for rendering and all kinds of other stuff potentially. The model that your action takes in should really only have the exact properties that are meant to be bound and any validations that are relevant.
Keith Rousseau