After the user fills out the first step of registration
information and clicks the next button, the user is created, the CreatedUser
event fires, and we fill in the appropriate information about the user into the
profile store.
The <asp:createuserwizard> control then displays the
second step template we’ve defined. This template lists all of the roles
currently created in the ASP.NET Role Management system, and allows the user to
select which roles they belong to:
Figure 3
Note that you’d typically never assign roles to an end-user
this way (instead you’d add your own logic to somehow calculate which role they
belong in), but I thought this scenario was cool nonetheless which is why it
works like the sample above.
I think it is cool because of the way we populate and access
these roles in the template of the <asp:createuserwizard>. Basically, we
have a template definition to the .aspx like this:
Listing 3
<asp:WizardStep runat="server" AllowReturn="False"
OnActivate="AssignUserToRoles_Activate"
OnDeactivate="AssignUserToRoles_Deactivate">
<table>
<tr>
<td>
Select one or more roles for the user:
</td>
</tr>
<tr>
<td>
<asp:ListBox ID="AvailableRoles" runat="server"
SelectionMode="Multiple" >
</asp:ListBox>
</td>
</tr>
</table>
</asp:WizardStep>
It simply contains a <asp:listbox> control named
“AvailableRoles”. When this wizard step is loaded (after the user hits the
next button on the first step in the wizard), it will fire the “OnActivate”
event. We can use this to databind the list of all roles in the system to the
above listbox. When the user hits next again, the wizard will fire the
“OnDeactivate” event. We can then use this to determine which roles were
selected in the above listbox, and use them to update the role-manager system.
The code to-do both of these actions looks like this:
Listing 4
// Activate event fires when user hits "next" in the CreateUserWizard
public void AssignUserToRoles_Activate(object sender, EventArgs e) {
// Databind list of roles in the role manager system to listbox
AvailableRoles.DataSource = Roles.GetAllRoles(); ;
AvailableRoles.DataBind();
}
// Deactivate event fires when user hits "next" in the CreateUserWizard
public void AssignUserToRoles_Deactivate(object sender, EventArgs e) {
// Add user to all selected roles from the roles listbox
for (int i = 0; i < AvailableRoles.Items.Count; i++) {
if (AvailableRoles.Items[i].Selected == true)
Roles.AddUserToRole(CreateUserWizard1.UserName, AvailableRoles.Items[i].Value);
}
}
That is all of the code for the CreateNewWizard.aspx.cs file
– 17 lines total if you omit comments and whitespace (if my count is right).