2

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>

1
  • If i were you, i would make separate views for user and admins, as this is a principle in SOLID principles, just to reduce the if statements in project and if want to make a change for admin or user only then this will make sense for you, hope i helped you. Commented Nov 5, 2018 at 18:13

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

So the code would essentially remain the same, but rather than calling User.IsInRole(), i would check the Model.IsAdmin property of my model?
Yes. It looks like your current model is a list of some sort. Move this into a separate Model class where you can add additional properties like 'IsAdmin'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.