如何在 Razor 视图中显示其他模型列?

Edw*_*d.K 3 c# asp.net-mvc razor asp.net-mvc-4

目前,我可以在 userRole 模型的 razer 视图中显示所有列。只是好奇我是否想在 UserRole Razor 视图中显示 SiteName 列,而不是显示 SiteID,这可能吗?我知道它可以通过自定义视图模型来完成,但这是必须的吗?如果我错了请纠正我!

用户角色模型:

    public int UserID { get; set; }
    public string UserName { get; set; }
    public int SiteID { get; set; }
    *No SiteName column here....so i only can show SiteID in razor..
Run Code Online (Sandbox Code Playgroud)

场地模型:

public int SiteID { get; set; }
public string SiteName { get; set; } <<-- the column i want..
Run Code Online (Sandbox Code Playgroud)

控制器:

public ActionResult Index()

    {
         //need join table here perhaps?

         return View(db.User_Role.ToList());
    }
Run Code Online (Sandbox Code Playgroud)

剃刀视图:

@model IEnumerable<FAB_Portal_POC.Models.UserRole>

<table class="table table-striped table-hover">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.UserName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Role)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SiteID)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Role)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SiteID) <<-- i want site name.
        </td>      
    </tr>
}
</table>
Run Code Online (Sandbox Code Playgroud)

Cod*_*ter 5

第一个问题是您的UserRole实体模型似乎没有导航属性。

您不需要这样做,但是查询会变得很尴尬:

var rolesWithSite = from r in db.User_Role
                    join s in db.Sites on s.ID equals r.Site_ID
                    select new
                    {
                        Role = r,
                        Site = s
                    }
                    .ToList();
Run Code Online (Sandbox Code Playgroud)

当您添加导航属性时(甚至可能代替外键属性):

public class User_Role
{
    public int UserID { get; set; }
    public string Role { get; set; }
    public string UserName { get; set; }
    public virtual Site Site { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

查询将变得更加容易:

var rolesWithSite = db.User_Role.Include(r => r.Site).ToList();
Run Code Online (Sandbox Code Playgroud)

然后你可以引入一个视图模型:

public class UserRoleViewModel
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public string Role { get; set; }
    public string Site { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并将查询结果映射到:

var viewModels = rolesWithSite.Select(r => new UserRoleViewModel
{
    UserID = r.UserID,
    UserName = r.UserName,
    Role = r.Role,
    Site = r.Site.SiteName,

}).ToList();

return View(viewModels);
Run Code Online (Sandbox Code Playgroud)