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

Viewed 5587

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 :)

2 Answers
Related