Umair Anwaar
Umair Anwaar

Reputation: 1138

How to access User Identity detail in mvc HtmlExtension method?

hellow guys thanks for your reply in advance.

I have to display many action links in many pages and I have authorization between user Roles so i am were coding if else in views but i wanna make it short thats why i go for htmlHelper extension method here is my code.

   public static MvcHtmlString ValidationActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string AllowedRole)
{
     if (User.IsInRole(AllowedRole))// its given me error The User dosent exist in current context Am i missing some namespace or what ?
     {
                htmlHelper.ActionLink(linkText, actionName);
     }                      
}

Upvotes: 2

Views: 65

Answers (1)

user3559349
user3559349

Reputation:

You can access User within the extension method using

public static MvcHtmlString ValidationActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string AllowedRole)
{
    var user = htmlHelper.ViewContext.HttpContext.User;

alternatively, you could pass User to the method by adding an additional parameter to your extension method.

Upvotes: 1

Related Questions