Can I load the Roles attribute in <asp: RoleGroup> programmatically?
I support the ASP.NET application, and now security is defined in different places on the site. There is some logic in the code, for example if User.IsInRole(...) , and all ASPX pages have different logic, for example:
<asp:LoginView ID="lvDoSomeStuff" runat="server"> <RoleGroups> <asp:RoleGroup Roles="Accounting,HR,Blah"> ... </RoleGroups> </asp:LoginView> As new feature requests appear and new roles are created, I have to go through the entire application and make sure that I have not missed any areas. I would like to avoid this in the future.
How can I set the Roles attribute of the <asp:RoleGroup> element programmatically? I tried to do something like this:
<asp:LoginView ID="lvDoSomeStuff" runat="server"> <RoleGroups> <asp:RoleGroup Roles="<%= UserManager.GetRolesThatCanDoX() %>"> ... </RoleGroups> </asp:LoginView> where GetRolesThatCanDoX() returns a comma-separated list of role names, but my method never calls a call.
Is it possible to do something similar in ASP.NET WebForms? Please help me parse my code !; -)
Solution: Phantomtypist's answer worked fine. My implementation was as follows:
Aspx:
<asp:LoginView ID="lvDoSomeStuff" runat="server"> <RoleGroups> <asp:RoleGroup> ... </asp:RoleGroup> </RoleGroups> </asp:LoginView> Code for:
protected void Page_Load(object sender, EventArgs e) { // Load rolegroups from UserManager lvDoSomeStuff.RoleGroups[0].Roles = UserManager.GetRolesThatCanDoStuff().ToArray(); lvDoSomeOtherStuff.RoleGroups[0].Roles = UserManager.GetRolesThatCanDoOtherStuff().ToArray(); } Have you tried something like this ...
code:
protected void Page_Load(Object sender, EventArgs e) { RoleGroup rg = new RoleGroup(); rg.ContentTemplate = new CustomTemplate(); String[] RoleList = {"users"}; rg.Roles = RoleList; RoleGroupCollection rgc = LoginView1.RoleGroups; rgc.Add(rg); } Designer:
<asp:LoginView id="LoginView1" runat="server"> <AnonymousTemplate> You are not logged in.<br /> <asp:LoginStatus id="LoginStatus1" runat="server"></asp:LoginStatus> </AnonymousTemplate> <LoggedInTemplate> You are logged in as <asp:LoginName id="LoginName1" runat="server" />. This message is not from the template.<br /> <asp:LoginStatus id="Loginstatus2" runat="server"></asp:LoginStatus> </LoggedInTemplate> </asp:LoginView>