开发者

ASP.NET MVC Generic Partial

开发者 https://www.devze.com 2022-12-30 02:36 出处:网络
Is is possible to have a pa开发者_如何转开发rtial view inherit more than one model? I have three models (Contacts, Clients, Vendors) that all have address information (Address). In the interest of bei

Is is possible to have a pa开发者_如何转开发rtial 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.


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.


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.


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号