I have a view that lists tables being added to a floor plan. Tables derive from TableInputModel to allow for RectangleTableInputModel, CircleTableInputModel, etc
The ViewModel has a list of TableInputModel which are all one of the derived types.
I have a partial view for each of the derived types and given a List of mixed derived types the framework knows how to render them.
However, on submitting the form the type information is lost. I have tried with a custom model binder but because the type info is lost when it’s being submitted, it wont work…
Has anyone tried this before?
Assuming you have the following models:
And the following controller:
Now you could write views.
Main view
Index.cshtml:and the corresponding editor templates.
~/Views/Home/EditorTemplates/RectangleTableInputModel.cshtml:~/Views/Home/EditorTemplates/CircleTableInputModel.cshtml:and final missing peace of the puzzle is the custom model binder for the
TableInputModeltype which will use the posted hidden field value to fetch the type and instantiate the proper implementation:which will be registered in
Application_Start:and that’s pretty much all. Now inside the Index Post action the model array will be properly initialzed with correct types.