ASP.NET Web Pages - Add User to Role

[ This is a 5 part tutorial; previous tutorial, Add Roles ]

Create a new file in the folder Private and name it AddUserToRole. Next copy this:




    var db = Database.Open("StarterSite");
    var SQLUSER = "SELECT Email FROM UserProfile";
    var users = db.Query(SQLUSER);
    var roles = Roles.GetAllRoles();//GET ALL ROLES

    var msg="";

    if (IsPost){
        var user = Request["user"];
        var role = Request["role"];

       if (!user.IsEmpty() && !role.IsEmpty()){//MAKE SURE USER AND ROLE IS NOT EMPTY
           if(!Roles.IsUserInRole(user, role)){//MAKE SURE USER IS NOT IN THE CURRENT ROLE.
               Roles.AddUsersToRoles(new[]{user}, new[]{role});//ADD USER TO ROLE
               msg = user + " Has been added to the role " + role;
               msg = user + " Is already in role " + role;
               msg = role + " No Longer Exist!";

This is similar to the previous page however this time we get the current created roles and users in the database. Then on posting we request the values of the HTML elements and add the user to the roles. We make sure that the fields are not empty and we make sure that the user is not in the current role. If everything is fine, we add the user to the role.


<form method="post">
    <p style="color:#a33f3f">@msg</p>

<legend>Add user to role</legend>

<div class="elements">
    <label for="user">User:</label>
    <select name="user" id="user">
    @foreach (var person in users){

    <div class="elements">
    <label for="role">Role:</label>
    <select name="role" id="role">
    @foreach (var uRole in roles){

    <input type="submit" class="submitform"/>


Add the registered account you made in Part 1 to the admin role.

[ continue, Remove User from Role ]