加入linq查询后如何打印

时间:2011-03-15 08:30:21

标签: c# asp.net linq asp.net-mvc-3

我有这段代码:

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

}

此代码在我的Controller中,我想运行此查询,然后将结果打印到我的视图中,我将如何编写视图?

3 个答案:

答案 0 :(得分:1)

    //if your question is how to display(Print!) a view for above query then in ActionResult Index()
    //1] As as best practise always Create a ViewModel - UserViewModel
      public class UserviewModel
      {
        public string Username {get;set;}
        public string Address {get;set;}
      }

    //2] Assign db.user values to UserviewModel or you can use Automapper

    //and 3] then return this viewmodel to view  
    return View(UserviewModel);

答案 1 :(得分:0)

此代码无法工作,因为您的LINQ查询返回匿名对象,因此您无法强烈键入视图。因此,第一步是定义一个视图模型,该模型将代表您愿意在视图中显示的信息:

public class UserViewModel
{
    public string UserName { get; set; }
    public DateTime LastActivityDate { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

然后在您的控制器操作中,您将返回此视图模型的集合:

public ActionResult Index()
{
    var currentUser = Membership.GetUser();
    var 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 UserViewModel
        {
            UserName = m.UserName, 
            LastActivityDate = m.LastActivityDate,
            Address =  m2.Address, 
            City = m2.City, 
            State = m2.State, 
            Zip = m2.Zip
        };
    return View(users);
}

最后在你的强类型视图中:

@model IEnumerable<AppName.Models.UserViewModel>
@Html.DisplayForModel()

并在相应的显示模板(~/Views/Shared/DisplayTemplates/UserViewModel.cshtml)中为集合的每个项目呈现:

@model AppName.Models.UserViewModel
<div>
    Username: @Html.DisplayFor(x => x.UserName)<br/>
    Last activity: @Html.DisplayFor(x => x.LastActivityDate)<br/>
    ...
</div>

答案 2 :(得分:0)

您需要获取用户类型并创建该类型的列表视图。创建视图的最简单方法是右键单击控制器方法并选择“创建视图”。这将确保路由也正确完成。