Timsen
Timsen

Reputation: 4116

Show admin panel button only if user is logged in and is in admin role

Basicly my questions is based on this question here:

Show menu item only for logged-on users

The way they solved it in previouse question is a hacky way. I read a little about this problem, and found out that you have to create custom HTML Helper, which going to show or hide button based on user Role.

So it in View it will looks something like :

 @HTML.MyCustomHelperWhichShowButton("ButtonText"); 

But how should I implement such a helper?

Upvotes: 0

Views: 1130

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

But how should I implement such a helper?

By writing an extension method to the HtmlHelper class:

public static class HtmlExtensions
{
    public static IHtmlString MyCustomHelperWhichShowButton(this HtmlHelper html, string text)
    {
        var isAuthnticated = html.ViewContext.HttpContext.User.Identity.IsAuthenticated;
        if (isAuthnticated)
        {
            return html.ActionLink(text, "MyListings", "List");
        }

        return new HtmlString(string.Empty);
    }
}

and by adding the namespace in which you defined this class to the <namespaces> section of your ~/Views/web.config file which will bring this helper into scope in all your views.

Upvotes: 1

Related Questions