0

I have working code for adding role to user. Now i want to replace text input by dropdownlist with available (all) roles in application. I now that there is html tag @Html.DropDownListFor so I created new ViewModel containing every data I need but now i'am in dead end. I try foreach and fill data for every item on list but then it doesn't work. Trying with @Htm.DropDownListFor have the same effect. Can someone can show me the right way how to do that ? Thanks !

Controller:

  public async Task<IActionResult> AddRoleToUser(string id, string role)
{
   var user = await _userManager.FindByIdAsync(id);

   if (await _roleManager.RoleExistsAsync(role))
   {
      await _userManager.AddToRoleAsync(user, role);
   }

   return RedirectToAction("UserGroups", new { id });
}

ViewModel:

 public class UserGroupsViewModel
 {
    public ApplicationUser ApplicationUser { get; set; }
    public IList<string> RolesList { get; set; }
    public IQueryable<ApplicationRole> AllRoles { get; set; }
 }

View

@model AdminMVC.Models.Admin.UserGroupsViewModel
@using (Html.BeginForm("AddRoleToUser", "Admin", new { id = Model.ApplicationUser.Id }))
 {
    <div classs="input-group">
       <p><b>Name new role for user:</b></p>
       <input class="form-control form-control-sm" type="text" name="role" placeholder="Role name">
       <span class="input-group-btn">
          <input type="submit" value="Add Role" class="btn btn-primary btn-sm" />
       </span>
    </div>
 }

My question has been identified as a possible duplicate of another question. But i saw that question and still cant do it. Can I must change my IList to list containing two values id and string ? And add additional position in viewmodel to store the result?

MarcinAWK
  • 63
  • 1
  • 11
  • 4
    Possible duplicate of [ASP.NET MVC 4 ViewModel with DropDownList data](https://stackoverflow.com/questions/14654873/asp-net-mvc-4-viewmodel-with-dropdownlist-data) – demo Feb 22 '19 at 14:37

1 Answers1

1

Change your RolesList to a SelectList and add a role property:

public SelectList RolesList { get; set; }
public string Role{get;set;}

Build the SelectList with

model.RolesList = new SelectList(listOfRoles);

Then in your view

@Html.DropDownListFor(x => x.Role, Model.RolesList)

If everything is in order, your post should contain the role populated.

mxmissile
  • 11,464
  • 3
  • 53
  • 79