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?
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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With