mmssaann
mmssaann

Reputation: 1507

create generic mvc view in mvc4

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

Answers (4)

Dheemanth Anand
Dheemanth Anand

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

ele2a
ele2a

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

JotaBe
JotaBe

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:

  • keep the common part (menu, header, footer...) on the site layout
  • make a view for each kind of object
  • make a view for each kind of list. in this vie you can use the object's view as a partial view and render it as many times as object are on the list.

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.DisplayForin 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

NinjaNye
NinjaNye

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

Related Questions