遵循最佳实践,是否有更好的方法根据用户角色显示/隐藏控件,还是在视图内部使用 User.IsInRole()是完全可以接受的吗?对的回答说,这违反了关注点分离。有哪些替代方案?
@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>
答案 0 :(得分:2)
就个人而言,我会在模型“ IsAdmin”中添加bool属性,并在控制器中设置该值。这样,您的视图仅适用于模型。