gpt4 book ai didi

c# - 如何在 Razor View 中显示其他模型列?

转载 作者:行者123 更新时间:2023-11-30 14:50:47 25 4
gpt4 key购买 nike

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

用户角色模型:

    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..

网站模型:

public int SiteID { get; set; }
public string SiteName { get; set; } <<-- the column i want..

Controller :

public ActionResult Index()

{
//need join table here perhaps?

return View(db.User_Role.ToList());
}

Razor View :

@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>

最佳答案

第一个问题是您的 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();

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

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

查询将变得更加容易:

var rolesWithSite = db.User_Role.Include(r => r.Site).ToList();

然后您可以引入一个 View 模型:

public class UserRoleViewModel
{
public int UserID { get; set; }
public string UserName { get; set; }
public string Role { get; set; }
public string Site { get; set; }
}

并将查询结果映射到:

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

}).ToList();

return View(viewModels);

关于c# - 如何在 Razor View 中显示其他模型列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35913190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com