Reputation: 389
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>(@[email protected]) @g.Result</th>
@if (User.IsInRole("Admin"))
{
<th> @Html.ActionLink("Edit", "Edit", new { id = g.GameId })</th>
}
</tr>
}
</tbody>
</table>
Upvotes: 2
Views: 2043
Reputation: 1028
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
}
Upvotes: 4