views:

126

answers:

1

In a MVC project am trying to create a view which has the Title from a parent table and the subsequent list below it from its related Child table.

I pulled the tables into the project using Entity Framework and in the controllers namespace created the follwing Viewmodel:

public class ServicesViewModel
{
    public ServicesViewModel(List<ServiceGroup> servicegroups, List<Service> services)
    {
        this.ServiceGroups = servicegroups;
        this.Service = services;
    }

    public List<ServiceGroup> ServiceGroups { get; set; }
    public List<Service> Service { get; set; }

}

Then in the controller Actionresult I did this:

    public ActionResult Index()
    {

        var servicegroups = _db.ServiceGroupSet.ToList();
        var services = _db.ServiceSet.ToList();

        return View(new ServicesViewModel(servicegroups,services));
    }

..And in the View did this:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

Other html code etc..

<% foreach (var m in Model.ServiceGroups) { %>

    <strong><ul> <%= m.ServiceGroupName %></ul></strong>

<% foreach (var item in Model.Service) { %>

    <li> <%= item.ServiceDescription %></li>

<% } %>


<% } %>

It all wires up ok but runs ALL child records for each parent record. I have not figured how to put that parameter which filters into the view.

I tried a linq query in the controller but can't seem to find the foreign key field in the intellisense.

+1  A: 

Hmmm.. if it is a Master-Detail 2 tables and you want to have a separate view model, I'd recomend that you define you as ServiceGroup + List and then pass list of this to view.

But if Your Service and ServiceGroup do have their own navigation properties (EF or LINQ2SQL). You can just pass ServiceGroups to view and there use Navigation Property ServiceGroup.Services to enumerate details.

<% foreach (var m in Model.ServiceGroups) { %>

    <strong><ul> <%= m.ServiceGroupName %></ul></strong>

**<% foreach (var item in m.Services) { %>**

    <li> <%= item.ServiceDescription %></li>

<% } %>


<% } %>
Alexander Taran
Thanks a lot, that worked
Paul Connolly