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.
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.
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.