使用 linq 从两个表中获取数据(连接)并将结果返回到视图中 [英] Get data from two tables(join) with linq and return result into view
问题描述
我有两个表:Projects 和 ProjectsData,我想使用 join 执行查询并在视图中获取结果.
I have two tables: Projects and ProjectsData and I want to execute query with join and get the result in the View.
在控制器中我有这个代码:
In the Controller I have this code:
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
}
但它不起作用...
推荐答案
在您看来,您正在尝试访问 pd
属性,但该属性不存在.该属性称为 ProjectData
.
In your view you are trying to access a pd
property but such property doesn't exist. The property is called ProjectData
.
话虽如此,我强烈建议您使用视图模型和强类型视图,而不是 ViewBag
.通过这种方式,您还将在视图中获得 Intellisense,这将帮助您选择正确的名称.
This being said I would strongly recommend you to use view models and strongly typed views instead of ViewBag
. This way you will also get Intellisense in your view which would have helped you pick the correct names.
因此,您可以首先定义一个视图模型,该模型将保存您的视图所需的所有信息:
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>
}
这篇关于使用 linq 从两个表中获取数据(连接)并将结果返回到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!