0

I have my menu toolbar in my _Layout, and sometimes I would like to hide submenu, depends on who is connected (administrator or user).

User profile is stored in userViewModel, but I can't set userViewModel in my _layout.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Cooxkie
  • 6,740
  • 6
  • 22
  • 26

1 Answers1

1

You can render menu toolbar in the _Layout by means of

@Html.Action("MenuToolbar","Controller")

public ViewResult MenuToolbar()
{
  if (user.isAdministrator) 
     return View("MenuToolbar");
  else return View("Empty");
}

OR you can use more universal approach:

public static  MvcHtmlString ActionBaseRole(this HtmlHelper value, string actionName, string controllerName, object routeValues , IPrincipal user)
 {     
   bool userHasRequeredRole = false;
   Type t = Type.GetType((string.Format("MyProject.Controllers.{0}Controller",controllerName))); // MyProject.Controllers... replace on you namespace
   MethodInfo method = t.GetMethod(actionName);
   var attr = (method.GetCustomAttribute(typeof(AuthorizeAttribute), true) as AuthorizeAttribute);
   if (attr != null)
   {
      string[] methodRequeredRoles = attr.Roles.Split(',');
      userHasRequeredRole = methodRequeredRoles.Any(r => user.IsInRole(r.Trim())); // user roles check in depends on implementation authorization in you site  
                                                                                            // In a simple version that might look like                                                                         
   }
   else userHasRequeredRole = true; //method don't have Authorize Attribute
   return userHasRequeredRole ? value.Action(actionName, controllerName, routeValues) : MvcHtmlString.Empty; 
 }

In this case you need just put [Authorize(Roles = "Administrator, OtherRole")] befor an action.

Ilya Sulimanov
  • 7,636
  • 6
  • 47
  • 68
  • Thanks, your first solution was exactly what I'm looking for. Sometimes it's hard to find simplest way ... :-) – Cooxkie May 31 '16 at 21:20