vb.net ASP.NET MVC 4,一个视图中的多个模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15844215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC 4, multiple models in one view?
提问by Calvin
I'm working on a little project in which we have a table of engineers, a table of projects, and a table of elements. engineers are assigned multiple elements, and elements can have multiple projects. I was just wondering how I would go about showing all the elements a engineer is apart of.
我正在做一个小项目,其中有一个工程师表、一个项目表和一个元素表。工程师被分配多个元素,元素可以有多个项目。我只是想知道我将如何展示工程师所拥有的所有元素。
Currently, I have a table created that associates a engineer with a element. it looks a little like this:
目前,我创建了一个将工程师与元素相关联的表。它看起来有点像这样:
[Engineer Elements]
[Engineer ID][Element ID]
[1] [2]
[1] [4]
[2] [2]
[2] [8]
So I do have a way to link the two tables. Could push me into the right direction on learning a bit more on linking these tables together using MVC?
所以我确实有办法链接这两个表。可以推动我学习更多关于使用 MVC 将这些表链接在一起的正确方向吗?
回答by p.s.w.g
If you don't already have a view model to represent this, just create one:
如果您还没有视图模型来表示这一点,只需创建一个:
public class MyViewModel
{
public Engineer Engineer { get; set; }
public List<Element> Elements { get; set; }
}
Populate a set of view models in the controller
在控制器中填充一组视图模型
public ActionResult MyAction()
{
var viewModels =
(from e in db.Engineers
select new MyViewModel
{
Engineer = e,
Elements = e.Elements,
})
.ToList();
return View(viewModels);
}
And in your view just specify that you're using a collection of view models:
在您的视图中,只需指定您正在使用一组视图模型:
@model List<MyViewModel>
@foreach(var vm in Model)
{
<h1>Projects for engineer: @vm.Engineer.Name</ha>
<ul>
@foreach(var ele in vm.Elements)
{
<li>@ele.Name</li>
}
</ul>
}

