Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change @model directive to a different model in razor view?

I have a controller that creates a model and calls a view passing the model as a parameter. In the View there is a @model directive specifying the type of Model. I want to reuse the same View, but pass a different model from the controller. Is it possible to dynamically (or conditionally) change @model directive in the View?

For instance, in my controller action:

var contactsModel = db.GetContacts();
var companiesModel = db.GetCompanies();
return (someCondition)? View(contactsModel):View(companiesModel);

Then how can I define @model in a View directive to satisfy both models? I want the same view to render the information based on the type of model passed.

Thank you.


UPDATE:

Thanks, but I need to use one common View only with different models.

It is possible, here is how this could be done.

In a View I define:

@model IEnumerable<MvcApplication1.Models.IBaseInterface>

In the Model class I define:

public interface IBaseInterface { }

public class Contact: IBaseInterface {}

public class Company: IBaseInterface {}

Then, in a View I use:

@if (Model is List<Contact>) {
    @foreach (var item in (List<Contact>)Model)
        { // Here item has type Contact }
}

@if (Model is List<Company>) {
    @foreach (var item in (List<Company>)Model)
        { // Here item has type Company }
}

Works perfectly :)

like image 529
monstro Avatar asked Jul 14 '12 22:07

monstro


1 Answers

Is it possible to dynamically (or conditionally) change @model directive in the View?

No.

If you need to pass different models this means that you need different views:

return (someCondition) 
    ? View("Contacts", contactsModel) 
    : View("Companies", companiesModel);\

A fundamental rule in ASP.NET MVC is the following: a view model per view.

like image 148
Darin Dimitrov Avatar answered Oct 03 '22 13:10

Darin Dimitrov