Reputation: 1507
I have raised similar question before, have got no answers.
How can I create a generic mvc4 view that can display list of or a single model that is passed to it. model can be either Person or Organization or Party whatever that is passed to it.
Upvotes: 3
Views: 7876
Reputation: 11
To achieve a Generic View Use below code. dynamic is an inbuilt keyword that accepts any model.It worked fine for me
@model dynamic
or
@model IEnumerable<dynamic>
Upvotes: 1
Reputation: 37
@model MyViewModel<IViewModel>
If you define a model like this then this error occurs:
Server Error in '/' Application.
The model item passed into the dictionary is of type MyViewModel\'1[Person]
, but this dictionary requires a model item of type MyViewModel'1[IViewModel]
.
Upvotes: 1
Reputation: 39015
Please, DON'T DO THAT!!
You should make a view for each kind of object / list of objects.
However, yu can still reuse elements:
Another possibility is to make templates for "Display For" for each kind of object. You can define a view for each kind of object, and store it in an special folder. When you use Html.Display
or Html.DisplayFor
in your templates, the system will choose and render the right template depending on the type of the object to display. (You could also make named templates, and select them by name). For an introduction on this technique, look at this excellent posts by Brad Wilson.
But I insist, please, don't make a "generic view", as this will add extra complexity (check if it's a list or a simple object, get the type of the object, choose how to display it and display it). You can make very simple views by reusing the elements as explained, and letting the controllers decide which view to show for each object or list of object. Or use templates. In this way your system will be easier to maintain and less prone to errors because of added complexity (you don't need to change the same template all the time, but to add new templates, with very few code on them)
What I can't understand is why you want to have a simple view. What's the reason for it?
Upvotes: 4
Reputation: 7126
If you are looking for something like:
@model MyViewModel<T> where T : IViewModel
... then that is not supported by Razor.
You may be able to use something like this:
@model MyViewModel<IViewModel>
... that way you could define all types that could be passed as follows
public class Person : IViewModel { ... }
public class Organisation : IViewModel { ... }
public class Party : IViewModel { ... }
Upvotes: 8