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


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 .


The easy and nice solution would be to use view model and tie the view to that view model and from controller actions you can convert the models into view model and pass it to the view.

If you are a fan of dynamics and the the properties of the two models are same the other option is you can tie the view to dynamic model.

链接地址: http://www.djcxy.com/p/61544.html

上一篇: https页面上的哪些网址需要为https?

下一篇: 如何将@model指令更改为剃须刀视图中的不同模型?