传递参数化列表以使用Entity Framework在MVC中查看 [英] Passing parameterized list to view in MVC using Entity Framework

查看:216
本文介绍了传递参数化列表以使用Entity Framework在MVC中查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC项目中,我试图创建一个视图,该视图具有来自父表的标题以及来自其相关子表的下面的后续列表。

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.

使用Entity Framework和控制器命名空间中的表创建了以下Viewmodel:

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

}

然后在控制器Actionresult中, p>

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:


%>

其他html代码等。

" %>

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.

我在控制器中尝试了一个linq查询,但似乎在intellisense中找不到外键字段。

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

推荐答案

Hmmm ..如果它是一个Master-Detail 2表,并且你想要一个单独的视图模型,我建议您定义为ServiceGroup + List,然后传递此列表以查看。

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.

但如果您的服务和ServiceGroup有自己的导航属性(EF或LINQ2SQL)。
您可以传递ServiceGroups来查看并使用导航属性ServiceGroup.Services来枚举详细信息。

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>

<% } %>


<% } %>

这篇关于传递参数化列表以使用Entity Framework在MVC中查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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