简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM