简体   繁体   中英

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? 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. That way your View is only working with the Model.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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