单个视图中的多个模型 (C# MVC3) [英] Multiple Models in a Single View (C# MVC3)
问题描述
我使用的是 C# 和 MVC3.
I'm using C# and MVC3.
我有一个页面,例如学生列表,显示学生列表,这是数据库驱动的.同时我的菜单是数据库驱动的,所以我也必须把它发送到视图中.
I have a page, for example a Student list, that displays the list of students, which is database driven. At the same time my menu is database driven, so I also have to send it to the view.
如何将两个模型发送到一个视图?
How can I send both models to a single view?
推荐答案
您应该始终为您的视图创建单独的 ViewModel.从您的视图到域模型应该有一个抽象.在演示/教程中,他们通过简单地将视图强输入域模型来展示这一切,但这不是一个好策略.视图不应依赖于业务对象.
You should always create separate ViewModels for your views. There should be an abstraction from your Views to your Domain Models. In the demos/tutorials they show it all pretty and easy by simply strongly typing the Views to Domain Models but that's not a good strategy. The views should not be dependent on the business objects.
即使需要将域模型映射到另一个视图模型类,您也应该为当前场景以及所有其他视图实施 David Glenn 提出的解决方案.
You should implement David Glenn's proposed solution for your current scenario and also for all other views even if requires mapping the domain model to to another view model class.
如果你有一个顶部菜单> TopMenu.aspx
里面有多个局部视图 > StudentMenu.ascx
, ResultMenu.ascx
If you have lets say a top Menu > TopMenu.aspx
And you have multiple partial views inside it > StudentMenu.ascx
, ResultMenu.ascx
您将为顶部菜单创建一个视图模型 > TopMenuViewModel.cs
您还将为部分视图创建视图模型 > StudentMenuViewModel
、ResultMenuViewModel
等
You will create a View Model for Top Menu > TopMenuViewModel.cs
And you will also create view models for partial views > StudentMenuViewModel
, ResultMenuViewModel
etc.
并且您的 TopMenuViewModel 将同时拥有 >
and your TopMenuViewModel will have both >
class TopMenuViewModel
{
//all the stuff required in TopMenu.aspx
StudentMenuViewModel studentvm;
ResultMenuViewModel resultvm;
}
并且在 TopMenu.aspx
渲染部分时,您将传递相关的视图模型 >
and in TopMenu.aspx
when rendering the partial you will pass the relevant view model >
Html.RenderPartial('StudentView', Model.studentvm)
希望有意义
这篇关于单个视图中的多个模型 (C# MVC3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!