简体   繁体   English

ASP.NET MVC 基于用户角色显示 HTML

[英]ASP.NET MVC Display HTML Based on User Role

Following best practices, is there a better way to show/hide controls based on the user's role, or is it perfectly acceptable to use User.IsInRole() inside of a view?遵循最佳实践,是否有更好的方法根据用户的角色显示/隐藏控件,或者在视图中使用User.IsInRole()是否完全可以接受? An answer on this post says it violates separation of concerns. 这篇文章的答案说它违反了关注点分离。 What are the alternatives?有哪些替代方案?

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

Personally, I would add a bool property to the model IsAdmin and set the value in the controller.就个人而言,我会向模型IsAdmin添加一个 bool 属性并在控制器中设置该值。 That way your View is only working with the Model.这样你的视图只与模型一起工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM