2009-04-29 53 views
6

我想根據身份驗證狀態或角色顯示/隱藏視圖的某些部分。對於我的控制器操作,我擴展了ActionFilterAttribute,以便可以將某些操作歸於特定的操作。ASP.NET MVC如何應用基於角色或基於認證的視圖渲染?

<RequiresRole(Role:="Admin")> _ 
Function Action() as ActionResult 
    Return View() 
End Function 

是否有類似方式(歸屬),我可以在瀏覽使用? (所以不喜歡這樣的:How can I create a view that has different displays according to the role the user is in?

+1

爲什麼你必須爲此創建一個ActionFilterATtribute? Authorize屬性需要一個Roles參數。 – 2009-04-29 13:22:51

+0

哦對:-) 我創建了我自己的只是爲了學習 – Ropstah 2009-04-29 14:47:38

回答

6

您可以訪問用戶的登錄的角色,從這樣的觀點:

<% if (Page.User.IsInRole("Admin")) { %> 
     <td> 
      <%= Html.DeleteButton("delete", model.ID) %> 
     </td> 
<% } %> 

,也許您的擴展方法的東西,如:

public static string DeleteButton(this HtmlHelper html, 
    string linkText, int id) 
{ 
    return html.RouteLink(linkText, 
    new { ID = id, action = "Delete" }, 
    new { onclick = "$.delete(this.href, deleteCompleted()); return false;" }); 
} 

顯然,我正在使用JavaScript對我的控制器操作執行HTTP DELETE,以防止頁面抓取工具意外刪除數據以獲取我的頁面。在我的情況下,我用一個delete()方法擴展JQuery來補充HTTP動詞。

+0

好的,所以使用基於屬性的視圖渲染可能是不可能的。我應該去If語句... Thx – Ropstah 2009-05-04 10:04:21

0

我新這個存在,但花了一段時間才發現。下面是我在用的:

<asp:LoginView runat="server"> 
    <AnonymousTemplate> 
     You are not logged in yet. Please log in. 
    </AnonymousTemplate> 
    <RoleGroups> 
     <asp:RoleGroup Roles="Admin"> 
      <ContentTemplate> 
       You are an Admin. 
      </ContentTemplate> 
     </asp:RoleGroup> 
     <asp:RoleGroup Roles="Customers"> 
      <ContentTemplate> 
       You are a customer. 
      </ContentTemplate> 
     </asp:RoleGroup> 
    </RoleGroups> 
    <LoggedInTemplate> 
     Simple Log in check 
    </LoggedInTemplate> 
</asp:LoginView> 

這使您可以顯示不同的內容,根據他們的登錄狀態或憑據不同的用戶。

+0

這是WebForms。我相信原帖是關於MVC的。 – 2014-11-14 19:14:00