I’m maintaining an ASP.NET application, and right now security is defined in various places throughout the site. There is some logic in the code-behind, like if User.IsInRole(...), and there is other logic sprinkled throughout the ASPX pages like:
<asp:LoginView ID="lvDoSomeStuff" runat="server">
<RoleGroups>
<asp:RoleGroup Roles="Accounting,HR,Blah">
...
</RoleGroups>
</asp:LoginView>
As new feature requests come in and new roles are created, I am forced to go through the entire application and make sure I haven’t missed any areas. I’d like to avoid this in the future.
How can I set the Roles attribute of the <asp:RoleGroup> element programmatically? I’ve tried doing something like this:
<asp:LoginView ID="lvDoSomeStuff" runat="server">
<RoleGroups>
<asp:RoleGroup Roles="<%= UserManager.GetRolesThatCanDoX() %>">
...
</RoleGroups>
</asp:LoginView>
where GetRolesThatCanDoX() returns a comma-delimited list of role names, but my method never seems to get called.
Is it possible to do something like this in ASP.NET WebForms? Please help me decouple my code! 😉
Solution: Phantomtypist’s answer worked perfectly. My implementation of it was as follows:
ASPX:
<asp:LoginView ID="lvDoSomeStuff" runat="server">
<RoleGroups>
<asp:RoleGroup>
...
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
Code-behind:
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:
Designer: