ASP.NET MVC 4,多个模型在一个视图? [英] ASP.NET MVC 4, multiple models in one view?

查看:99
本文介绍了ASP.NET MVC 4,多个模型在一个视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作中,我们有工程师的表,项目表,和元素的表的小项目。工程师们分配了多个元素,元素可以有多个项目。我只是想知道我怎么会去显示所有元素的工程师拆开的。

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]

所以,我有办法了两个表联系起来。可以把我推到正确的方向上学习更多的关于这些表连接在一起使用MVC?

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?

推荐答案

如果您还没有一个视图模型重新present这个,就创建一个:

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>
}

这篇关于ASP.NET MVC 4,多个模型在一个视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆