2009-11-17 40 views
3

嗨母版我有一個asp.net MVC Web應用程序的RenderPartial有條件在asp.net mvc的

<%Html.RenderPartial("AdminMenu"); %> 
<%Html.RenderPartial("ApproverMenu"); %> 
<%Html.RenderPartial("EditorMenu"); %> 

在我的母版定義以下菜單但是我想只顯示取決於登錄右鍵菜單在用戶角色中。我如何實現這一目標?

我開始認爲我的策略是不正確的,那麼是否有更好的方法來實現相同的目標?

回答

8

舉個簡單的例子,你可以這樣做:

<% 
    if (User.IsInRole("AdminRole") 
     Html.RenderPartial("AdminMenu"); 
    else if (User.IsInRole("Approver") 
     Html.RenderPartial("ApproverMenu"); 
    else if (User.IsInRole("Editor") 
     Html.RenderPartial("EditorMenu"); 
%> 

或者是你的用戶可以在多個角色,在這種情況下是這樣的邏輯可能更合適:

<% 
    if (User.IsInRole("AdminRole") 
     Html.RenderPartial("AdminMenu"); 
    if (User.IsInRole("Approver") 
     Html.RenderPartial("ApproverMenu"); 
    if (User.IsInRole("Editor") 
     Html.RenderPartial("EditorMenu"); 
%> 

或者使用擴展方法爲後者提供更優雅的方法:

<% 
    Html.RenderPartialIfInRole("AdminMenu", "AdminRole"); 
    Html.RenderPartialIfInRole("ApproverMenu", "Approver"); 
    Html.RenderPartialIfInRole("EditorMenu", "Editor"); 
%> 

public static void RenderPartialIfInRole 
    (this HtmlHelper html, string control, string role) 
{ 
    if (HttpContext.Current.User.IsInRole(role) 
     html.RenderPartial(control); 
} 
+0

是的,我希望的東西多了幾分優雅!但我同意這是一個工作。 – Rippo 2009-11-17 15:43:50

+0

感謝您的回答! – Rippo 2009-11-17 15:44:56

+1

@Rippo是的,我明白了。其實,你可以嘗試一種擴展方法。我會舉一個例子。 – Joseph 2009-11-17 15:45:33

2

擴展方法是去這裏的路。更普遍比@約瑟夫的RenderPartialIfInRole,你可以使用一個ConditionalRenderPartial方法:

<% 
    Html.ConditionalRenderPartial("AdminMenu", HttpContext.Current.User.IsInRole("AdminRole")); 
    Html.ConditionalRenderPartial("ApproverMenu", HttpContext.Current.User.IsInRole("ApproverRole")); 
    Html.ConditionalRenderPartial("EditorMenu", HttpContext.Current.User.IsInRole("EditorRole")); 
%> 

...

public static void ConditionalRenderPartial 
    (this HtmlHelper html, string control, bool cond) 
{ 
    if (cond) 
     html.RenderPartial(control); 
} 
+0

ConditionalRenderPartial是mvc v2方法嗎? – Rippo 2009-11-17 16:05:55

+0

@Rippo不,我提供了下面的實現,但是我忘了從'RenderPartialIfInRole'重命名它,這很令人困惑。現在修復。 – 2009-11-17 16:25:35

+0

@加貝啊,我這麼認爲!感謝編輯 – Rippo 2009-11-17 16:26:24

相關問題