如何在我的剃刀_Layout中隐藏子菜单?

时间:2016-05-31 15:56:41

标签: c# asp.net razor mvvm

我的_Layout中有我的菜单工具栏,有时我想隐藏子菜单,取决于谁连接(管理员或用户)。

用户个人资料存储在userViewModel中,但我无法在_layout中设置userViewModel。

1 个答案:

答案 0 :(得分:1)

您可以通过

在_Layout中渲染菜单工具栏

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

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

或者您可以使用更通用的方法:

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; 
 }

在这种情况下你需要放 [Authorize(Roles = "Administrator, OtherRole")]是行动。