Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4, multiple models in one view? [duplicate]

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?

like image 556
Calvin Avatar asked Apr 05 '13 21:04

Calvin


1 Answers

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>
}
like image 150
p.s.w.g Avatar answered Sep 28 '22 05:09

p.s.w.g