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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With