ASP.NET MVC 通用部分
部分视图是否可以继承多个模型?我有三个模型(联系人、客户、供应商),它们都有地址信息(地址)。为了保持 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您仍然可以保持 DRY 并拥有三个视图(联系人、客户、供应商),而不是使用复合视图模型。如果您担心在显示地址信息时重复自己,只需为该类型制作一个显示模板即可。这样,您就可以在每个联系人、客户和供应商自己的视图中写出他们的所有具体信息,然后直接插入:
现在您在保持干燥的同时仍然支持单一职责原则。
有关显示和编辑模板的更多信息,您可以查看 布拉德·威尔逊 或 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:
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:
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!