title: Can I load the 'Roles' attribute of an <asp:RoleGroup> programmatically?
body: <p>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 <code>if User.IsInRole(...)</code>, and there is other logic sprinkled throughout the ASPX pages like:</p>
  
  <pre><code>&lt;asp:LoginView ID="lvDoSomeStuff" runat="server"&gt;
      &lt;RoleGroups&gt;
          &lt;asp:RoleGroup Roles="Accounting,HR,Blah"&gt;
          ...
      &lt;/RoleGroups&gt;
  &lt;/asp:LoginView&gt;
  </code></pre>
  
  <p>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.</p>
  
  <p>How can I set the <code>Roles</code> attribute of the <code>&lt;asp:RoleGroup&gt;</code> element programmatically? I've tried doing something like this:</p>
  
  <pre><code>&lt;asp:LoginView ID="lvDoSomeStuff" runat="server"&gt;
      &lt;RoleGroups&gt;
          &lt;asp:RoleGroup Roles="&lt;%= UserManager.GetRolesThatCanDoX() %&gt;"&gt;
          ...
      &lt;/RoleGroups&gt;
  &lt;/asp:LoginView&gt;
  </code></pre>
  
  <p>where <code>GetRolesThatCanDoX()</code> returns a comma-delimited list of role names, but my method never seems to get called.</p>
  
  <p>Is it possible to do something like this in ASP.NET WebForms? Please help me decouple my code! ;-)</p>
  
  <p><strong>Solution:</strong> <a href="https://stackoverflow.com/questions/5106142/can-i-load-the-roles-attribute-of-an-asproelgroup-programmatically/5106195#5106195">Phantomtypist's answer</a> worked perfectly. My implementation of it was as follows:</p>
  
  <p><strong>ASPX:</strong></p>
  
  <pre><code>&lt;asp:LoginView ID="lvDoSomeStuff" runat="server"&gt;
      &lt;RoleGroups&gt;
          &lt;asp:RoleGroup&gt;
          ...
          &lt;/asp:RoleGroup&gt;
      &lt;/RoleGroups&gt;
  &lt;/asp:LoginView&gt;
  </code></pre>
  
  <p><strong>Code-behind:</strong></p>
  
  <pre><code>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();
  }
  </code></pre>