简体   繁体   English

使用linq从两个表(join)中获取数据并将结果返回到视图中

[英]Get data from two tables(join) with linq and return result into view

I have two tables: Projects and ProjectsData and I want to execute query with join and get the result in the View. 我有两个表:Projects和ProjectsData,我想用join执行查询,并在View中获取结果。

In the Controller I have this code: 在Controller中我有这个代码:

ViewBag.projectsData = (from pd in db.ProjectsData
                                   join p in db.Projects on pd.ProjectId equals p.ID
                                   where pd.UserName == this.HttpContext.User.Identity.Name 
                                   orderby p.Name, p.ProjectNo
                                   select new { ProjectData = pd, Project = p });

What I should use in the View to extract this data. 我应该在视图中使用什么来提取这些数据。 I tried that: 我试过了:

@foreach (var item in ViewBag.projectsData)
{
    @item.pd.UserName
}

but it doesn't work... 但它不起作用......

In your view you are trying to access a pd property but such property doesn't exist. 在您的视图中,您正在尝试访问pd属性,但此类属性不存在。 The property is called ProjectData . 该属性称为ProjectData

This being said I would strongly recommend you to use view models and strongly typed views instead of ViewBag . ViewBag我强烈建议你使用视图模型和强类型视图而不是ViewBag This way you will also get Intellisense in your view which would have helped you pick the correct names. 通过这种方式,您还可以在视图中获得Intellisense,这可以帮助您选择正确的名称。

So you could start by defining a view model that will hold all the information your view would need: 因此,您可以从定义视图模型开始,该模型将包含您的视图所需的所有信息:

public class MyViewModel
{
    public ProjectData ProjectData { get; set; }
    public Project Project { get; set; }
}

and then inside your controller action populate this view model and pass to the view: 然后在控制器内部操作填充此视图模型并传递给视图:

public ActionResult Index()
{
    var viewModel = 
        from pd in db.ProjectsData
        join p in db.Projects on pd.ProjectId equals p.ID
        where pd.UserName == this.HttpContext.User.Identity.Name 
        orderby p.Name, p.ProjectNo
        select new MyViewModel { ProjectData = pd, Project = p };
    return View(viewModel);
}

and finally inside your strongly typed view use the view model: 最后在强类型视图中使用视图模型:

@model IEnumerable<AppName.Models.MyViewModel>
@foreach (var item in Model)
{
     <div>@item.ProjectData.UserName</div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM