2016-05-31 4 views
0

내 _Layout에 내 메뉴 도구 모음이 있는데 때로는 누가 하위 메뉴를 숨기고 싶은지, 누가 연결되어 있는지 (관리자 또는 사용자)에 따라 다릅니다.내 면도기에서 하위 메뉴를 숨기는 방법 _Layout?

사용자 프로필은 userViewModel에 저장되어 있지만 _layout에는 userViewModel을 설정할 수 없습니다.

+0

기본적으로 user_profile == administrator 인 경우 메뉴 도구 모음을 표시 하시겠습니까? –

+0

http://stackoverflow.com/questions/4381189/accessing-a-session-object-from-razor-layout-cshml – CodeCaster

+0

ViewData 또는 ViewBag 사용 –

답변

1

당신은

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

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

에 의해 _Layout에서 메뉴 도구 모음을 렌더링하거나 더 보편적 인 접근 사용할 수 있습니다 : 당신은 그냥 을 넣을 필요는이 경우

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")] 조치를 취하십시오.

+0

감사합니다. 첫 번째 솔루션은 내가 찾고있는 것입니다. 때로는 가장 간단한 방법을 찾는 것이 어렵습니다. :-) – Cooxkie

관련 문제