I'm trying to add users to specific roles based on this tutorial. But when I tick the checkbox and submit the form, users cannot be added to the role as expected.
It shows that model.Count=0
from the post method.
EditUsersInRole.cshtml
@model List<UserRoleViewModel>
@{
var roleId = ViewBag.RoleId;
ViewBag.Title = "Edit Users in Role";
}
<h1>Add or Romove users from this role</h1>
<form asp-controller="Administration" asp-action="EditUsersInRole" method="post">
<div >
<div >
@if(Model.Count > 0)
{
@foreach(var user in Model)
{
<div >
<input type="hidden" asp-for="@user.UserId"/>
<input type="hidden" asp-for="@user.UserName"/>
<input asp-for="@user.isSelected" />
<label asp-for="@user.isSelected">@user.UserName</label>
</div>
}
}
<input type="submit" value="Update" />
<a asp-controller="administration" asp-action="editrole" asp-route-id = "@roleId" >Cancel</a>
</div>
</div>
</form>
EditUsersInRole POST method
[HttpPost]
public async Task<IActionResult> EditUsersInRole(List<UserRoleViewModel> model, string Roleid)
{
if (ModelState.IsValid)
{
var role = await roleManager.FindByIdAsync(Roleid);
if (role == null)
{
ViewBag.ErrorMessage = $"RoleId {Roleid} not found";
return View("NotFound");
}
foreach (var item in model)
{
var user = await userManager.FindByIdAsync(item.UserId);
var isInRole = await userManager.IsInRoleAsync(user, role.Name);
IdentityResult result = null;
if (item.isSelected && isInRole)
{
result = await userManager.AddToRoleAsync(user, role.Name);
}
else if (!item.isSelected && isInRole)
{
result = await userManager.RemoveFromRoleAsync(user, role.Name);
}
//if (!result.Succeeded).....
return RedirectToAction("EditRole", new {id = Roleid });
}
CodePudding user response:
You are not correctly pass the model as an array to the controller.
For the asp-for
tag helper, it should be
asp-for="@Model[i]./*Property*/"
@if (Model.Count > 0)
{
for (int i = 0; i < Model.Count; i )
{
<div >
<input type="hidden" asp-for="@Model[i].UserId"/>
<input type="hidden" asp-for="@Model[i].UserName"/>
<input asp-for="@Model[i].isSelected" />
<label asp-for="@Model[i].isSelected">@Model[i].UserName</label>
</div>
}
}
CodePudding user response:
You have to pass the model properties correctly
@model List<UserRoleViewModel>
@{
var roleId = ViewBag.RoleId;
ViewBag.Title = "Edit Users in Role";
}
<h1>Add or Romove users from this role</h1>
<form asp-controller="Administration" asp-action="EditUsersInRole" method="post">
<div >
<div >
@if(Model.Count > 0)
{
@if (Model.Count > 0)
{
for (int i = 0; i < Model.Count; i )
{
<div >
<input type="hidden" asp-for="@Model[i].UserId"/>
<input type="hidden" asp-for="@Model[i].UserName"/>
<input asp-for="@Model[i].isSelected" />
<label asp-for="@Model[i].isSelected">@Model[i].UserName</label>
</div>
}
}
}
<input type="submit" value="Update" />
<a asp-controller="administration" asp-action="editrole" asp-route-id = "@roleId" >Cancel</a>
</div>
</div>
</form>