Monday, November 10, 2014

Asp.Net MVC Dynamic View

Dynamic type view is not new, in this post i explain how a single view supports multiple types of Models.
As We know, a view created with dynamic type gets neither intellisense support nor strongly typed templated helpers and you have to deal with the model's properties which may be intrinsic or complex and may also be readonly.
In order to show you that a single view supports any type viewModel, i have created 3 Model classes:
Hotel - which contains basic and complex type properties. (complex type here List<HotelRoom>)
Customer - which contains basic and complex type properties. (complex type here is HotelRoom type)
HotelRoom - which contains only basic types.

These are the ViewModels passed to the view:
  1. List<HotelRoom>
  2. Hotel
  3. Customer
Below are the screenshots for each viewModel rendered by single view:
 ViewModel - List<HotelRoom>

ViewModel - Customer

ViewModel - Hotel

What View contains?
The view contains the logic to iterate over the ViewData.ModelMetadata.Properties to generate label and control for each field and also checks for readonly metadata for a field and injects disabled attribute into the html control.
For complex type handling whether its a property or ViewModel, calling the Editor() will takes care of rendering it. If the ViewModel type is a collection, we have to provide a custom EditorTemplate (partial view) for the type used in the collection.
Note: For a property which is applied with readonly metadata attribute on a Model, it doesn't get its value submitted (even if you use hidden field it doesn't works) means it gets null value when (form post) submitted.

I don't recommend this approach for real scenarios, consider it as an example case where you can learn something from its code.

This sample contains:
  • 2 View files (view, partial-view)
  • 1 Class file (contains 3 Models)
  • 1 Controller file (3 Get Action methods and 3 Post Action Methods)
You can find the above files for download (only MVC folders):
Dowload Link