views:

174

answers:

3

Is is possible to have a partial view inherit more than one model? I have three models (Contacts, Clients, Vendors) that all have address information (Address). In the interest of being DRY I pulled the address info into it's own model, Addresses. I created a partial create / update view of addresses and what to render this in other other three model's create / update views.

A: 

How about you create a new model that contains all three models (Contacts, Clients, Vendors) . Then pass this new model to your partial. From there you can have access to all three models from your newly created model.

gmcalab
I don't think he needs to render them all at the same time. He created a view that's used to render an address, and now wants to make a call to render that from inside the Contacts/Clients/Vendors views.
R0MANARMY
I initially had all three models in one, but their information was unique enough that it made sense to separate them. I do agree that this would be easier though.
gnome
A: 

I believe the only way to do this is with a composite view model (which is not necessarily a bad thing), so something like:

public class MyControllerActionViewModel
{
    public IList<Contact> Contacts { get; set; }
    public IList<Client> Clients { get; set; }
    public IList<Vendor> Vendors { get; set; }
}

We use this approach a lot to get more elements into the view when needed, and I see no bad practice in using these custom view models whenever needed.

Hope that helps!

Terry_Brown
Is there an echo in here?
gmcalab
only alpha males unfortunately ;)
Terry_Brown
doesn't matter since neither one of you gave the right answer
R0MANARMY
@R0MANARMY - Nobody asked your opinion.
gmcalab
@gmcalab: It's not an opinion, it's a fact. I didn't mean it in a "you didn't give the accepted answer" way. I meant it in a "you misunderstood the question and gave a completely irrelevant (and incorrect) answer."
R0MANARMY
@R0MANARMY - oh really, is that how you see it? I'm glad you think you're some sort of authority on here.
gmcalab
+2  A: 

Rather than using a composite view model, you can still be DRY and have three views (Contacts, Clients, Vendors). If you are concerned about repeating yourself when displaying the address information just make a display template for the type. That way you can write out all the specific information for each Contact, Client, and Vendor in their own views and just drop in:

<%= Html.DisplayFor(m => m.Address) %>

Now you are being DRY while still supporting the Single Responsibility Principle.

For more on Display and Edit templates you can look at Brad Wilson or Phil Haack posts on it.

Steve Hook
Isn't `Html.DisplayFor()` an ASP.NET MVC 2 feature?
Nate Bross
@Nate Bross Yes it is.
Steve Hook
Good answer and links. Will definitely read up on it!
gnome