gpt4 book ai didi

c# - ASP.NET MVC 根据用户角色显示 HTML

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:00 24 4
gpt4 key购买 nike

遵循最佳实践,是否有更好的方法来根据用户的角色显示/隐藏控件,或者在 View 内使用 User.IsInRole() 是否完全可以接受?关于 this post 的回答说它违反了关注点分离。有哪些替代方案?

@if(User.IsInRole("Admin"))
{
@Html.ActionLink("Create", "Create", "Games")
}

<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th>
<th scope="col">Home</th>
<th scope="col">Away</th>
<th scope="col">Field</th>
<th scope="col">Result</th>
@if (User.IsInRole("Admin"))
{
<th scope="col"></th>
}
</tr>
</thead>
<tbody>
@foreach (var g in Model)
{
<tr>
<th>@g.GameDate</th>
<th>@g.HomeTeam.TeamName</th>
<th>@g.AwayTeam.TeamName</th>
<th><a href="http://maps.google.com/?q=directions to @g.Ballpark.Street @g.Ballpark.City @g.Ballpark.StateId" target="_blank">@g.Ballpark.Name</a></th>
<th>(@g.HomeTeamRuns-@g.AwayTeamRuns) @g.Result</th>
@if (User.IsInRole("Admin"))
{
<th> @Html.ActionLink("Edit", "Edit", new { id = g.GameId })</th>
}
</tr>
}
</tbody>
</table>

最佳答案

就我个人而言,我会向模型 IsAdmin 添加一个 bool 属性,并在 Controller 中设置该值。这样您的 View 就只与模型一起工作。

@if (Model.IsAdmin)
{
// render admin elements
}

关于c# - ASP.NET MVC 根据用户角色显示 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52770979/

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