ASP.NET MVC 通用部分

发布于 2024-09-01 17:40:01 字数 131 浏览 1 评论 0原文

部分视图是否可以继承多个模型?我有三个模型(联系人、客户、供应商),它们都有地址信息(地址)。为了保持 DRY,我将地址信息提取到它自己的模型 Addresses 中。我创建了地址的部分创建/更新视图以及在其他三个模型的创建/更新视图中呈现的内容。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

回忆躺在深渊里 2024-09-08 17:40:01

您仍然可以保持 DRY 并拥有三个视图(联系人、客户、供应商),而不是使用复合视图模型。如果您担心在显示地址信息时重复自己,只需为该类型制作一个显示模板即可。这样,您就可以在每个联系人、客户和供应商自己的视图中写出他们的所有具体信息,然后直接插入:

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

现在您在保持干燥的同时仍然支持单一职责原则。

有关显示和编辑模板的更多信息,您可以查看 布拉德·威尔逊Phil Haack 在其上发帖。

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.

糖果控 2024-09-08 17:40:01

您可以创建一个包含所有三个模型(联系人、客户、供应商)的新模型吗?然后将这个新模型传递给您的部分。从那里您可以访问新创建的模型中的所有三个模型。

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.

温柔嚣张 2024-09-08 17:40:01

我相信做到这一点的唯一方法是使用复合视图模型(这不一定是坏事),所以类似:

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

我们经常使用这种方法来在需要时将更多元素添加到视图中,并且我认为没有什么不好的做法在需要时使用这些自定义视图模型。

希望有帮助!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文