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 开发者_StackOverflow中文版(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?
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.
精彩评论