从两个表(加入)的LINQ获取数据并返回结果进入视野
我有两个表:项目和ProjectsData我想加盟,执行查询并得到结果中查看
I have two tables: Projects and ProjectsData and I want to execute query with join and get the result in the View.
在控制器我有这个code:
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
}
,但它不工作...
but it doesn't work...
在你看来,你试图访问一个 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
。这样,你会在你认为获得智能感知这将帮助你选择正确的名称。
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>
}