join linq查询后如何打印
我有这段代码:
public ActionResult Index()
{
MembershipUser currentUser = Membership.GetUser();
Guid UserId = (Guid)currentUser.ProviderUserKey;
var users = from m in db.Users
join m2 in db.MyProfiles on m.UserId equals m2.UserId
where m.UserId == UserId
select new{UserName = m.UserName, LastActivityDate = m.LastActivityDate,
Address = m2.Address, City = m2.City, State = m2.State, Zip = m2.Zip};
return View(users);
}
这段代码在我的控制器中,我想运行这个查询,然后将结果打印到我的视图中,我将如何编写视图?
I have this code:
public ActionResult Index()
{
MembershipUser currentUser = Membership.GetUser();
Guid UserId = (Guid)currentUser.ProviderUserKey;
var users = from m in db.Users
join m2 in db.MyProfiles on m.UserId equals m2.UserId
where m.UserId == UserId
select new{UserName = m.UserName, LastActivityDate = m.LastActivityDate,
Address = m2.Address, City = m2.City, State = m2.State, Zip = m2.Zip};
return View(users);
}
This code is in my Controller, I want to run this query and then print the results into my view, how would I write the view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此代码无法工作,因为您的 LINQ 查询返回匿名对象,因此您无法强类型化您的视图。因此,第一步是定义一个视图模型,它将表示您愿意在视图上显示的信息:
然后在控制器操作中,您将返回该视图模型的集合:
最后在强类型视图中
:将为集合中的每个项目呈现相应的显示模板 (
~/Views/Shared/DisplayTemplates/UserViewModel.cshtml
):This code cannot work because your LINQ query is returning an anonymous object so you cannot strongly type your view. So the first step would be to define a view model which will represent the information you are willing to display on your view:
then in your controller action you would return a collection of this view model:
and finally in your strongly typed view:
and in the corresponding display template (
~/Views/Shared/DisplayTemplates/UserViewModel.cshtml
) which will be rendered for each item of the collection:您需要获取用户的类型并创建该类型的列表视图。创建视图的最简单方法是在控制器方法中右键单击并选择“创建视图”。这将确保路由也正确完成。
You need to get the type of users and make a List-View of that type. Easiest way to make a view is simply right-clicking in your controller method and selecting Create View. That'll make sure the routing gets done properly as well.