Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Assigning Roles to User in MVC 4 via Checkboxes

I am currently using MVC 4 with the Razor Engine and C# as the code behind logic. A customised version of the SimpleMembership database has been built to meet the requirements of the website.

The website can create and edit roles and users as intended, however I am having a problem assigning a role to a user. Some search results provide code to assign a particular role to a user on account creation. Our requirements are not to have this, instead we need to manually assign them using a UI via the website.

There are plenty of tutorials for ASP.Net (example below), however I am finding it difficult to locate a relevant tutorial for MVC 4.

http://www.asp.net/web-forms/tutorials/security/roles/assigning-roles-to-users-cs

After reading the above, I am asking the following questions.

Question One: Is there an MVC tutorial for assigning user roles via a UI? If so, can you provide a link to the tutorial.

Question Two: If you do not have a link to a tutorial, could you provide some advice on the following:

  • When an administrator loads the User Management UI a table will load up a list of users, when they click the edit button for a particular user the following will take effect and pass the data back to a view called 'Edit.cshtml'.

    public ActionResult Edit(int id = 0)
    {
      var userProfile = _db.UserProfiles.Find(id);
      if (userProfile == null)
      {
        Response.Redirect("~/UserManagement/PageNotFound");
      }
    
      return View(userProfile);
    }
    
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(UserProfile userProfile)
    {
      if (ModelState.IsValid)
      {
        _db.Entry(userProfile).State = EntityState.Modified;
        _db.SaveChanges();
        return RedirectToAction("Index");
      }
    
      return View(userProfile);
    }
    

Within the 'Edit' view I was thinking of rendering a partial view onto the page with checkboxes for various roles within the database. Something similar to the following:

@model IEnumerable<PROJECTNAME.DAL.Models.Role>

@foreach (var item in Model)
{
    @Html.LabelFor(m => item.RoleName)

    <label class="bolder">
        Visible
        @Html.CheckBoxFor(m => item.Visible)
        <span class="lbl"></span>
    </label>
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
     <!-- CODE HERE IS TO EDIT USER DETAILS -->

     <div id="assignableroles">
        @{
         Html.RenderPartial("_AssignableRoles");
        }
     </div>
    </fieldset>    
}

Once the relevant checkbox/es have been marked this should update into the database and give the user access to that particular area (as long as authorisation attributes have been added accordingly).

I did find this online, however I am not sure where to add this in a Controller or whether it is relevant to my predicament as I am considering using two views as I need to handle two different models.

  var role = (SimpleRoleProvider)Roles.Provider;

  if (!role.RoleExists(selectedRole))
    role.CreateRole(selectedRole);

  WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
  role.AddUsersToRoles(new[] { model.UserName }, new[] { selectedRole });

Apologies for the long post, however this is the first time I have used Membership within MVC and I am still fairly new to this tool.

Edit:

I have also ensured this was added to the web.config file:

<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
  <providers>
    <clear />
    <add name="SimpleRoleProvider"
         type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"
         connectionStringName="DefaultConnection" applicationName="PROJECTNAME" />
  </providers>
</roleManager>
like image 665
Damian Avatar asked Aug 07 '13 13:08

Damian


1 Answers

Simpliest way is to manipulate with following methods:

Roles.AddUserToRole(UserName, RoleName) - add role

Roles.RemoveUserFromRole(UserName, RoleName) - remove role

For example, to add role for user you may have following action result in your controller:

[HttpPost]
public ActionResult(string UserName, string RoleName)
{
 Roles.AddUserToRole(UserName, RoleName) 
return View()
}

string UserName, string Role - should be passed from View by post method.

like image 95
Andrey Gubal Avatar answered Nov 03 '22 05:11

Andrey Gubal