AnonyMouse
AnonyMouse

Reputation: 18630

How to make the view less complicated in regards to showing links only to certain users in ASP.NET MVC

I have an ASP.NET MVC view which needs a link to only be shown to certain user roles and only when it's in a particular state. I wrote it like this:

@if (!item.Validated && (HttpContext.Current.User.IsInRole("regionaladmin") || HttpContext.Current.User.IsInRole("superadmin")) {
    <input type="button" class="btnvalidate" value="Validate" [email protected] /> <span>|</span>
}

So this is getting a little messy.

Is there a better solution to tidy this up a bit?

Upvotes: 0

Views: 71

Answers (2)

Xavier Poinas
Xavier Poinas

Reputation: 19733

If the problem is with testing more than 1 role at a time, an extension method could help you:

public static bool IsInRole(this IPrincipal user, params string[] roles)
{
    return roles.Any(role => user.IsInRole(role));
}

From the view, you can also access the User object directly (no need to go through the WebContext). You code becomes:

@if (!item.Validated && User.IsInRole("regionaladmin", "superadmin"))
{
    ...
}

Upvotes: 1

John Weldon
John Weldon

Reputation: 40749

Refactor the 'Business Logic' into a single method and call that instead:

@if (ShouldSeeInvalidateButton(item)) {
   // ...
}

And your function:

private bool ShouldSeeInvalidateButton(Item item)
{
    return !item.Validated && ....
}

Upvotes: 2

Related Questions