gnome
gnome

Reputation: 1133

ASP.NET MVC Generic Partial

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.

Upvotes: 0

Views: 929

Answers (3)

Steven Hook
Steven Hook

Reputation: 902

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.

Upvotes: 2

Terry_Brown
Terry_Brown

Reputation: 1408

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!

Upvotes: 0

Gabe
Gabe

Reputation: 50493

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.

Upvotes: 0

Related Questions