Passing parameterized list to view in MVC using Entity Framework

核能气质少年 提交于 2019-12-11 06:54:14

问题


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:

" %>

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:


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>

<% } %>


<% } %>


来源:https://stackoverflow.com/questions/1985333/passing-parameterized-list-to-view-in-mvc-using-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!