I have been struggling to assign roles to users by a single person on ASP.NET MVC. I have used a view bag on a controller and a dropdown list on the view. When I assign roles, it is not saved on the database. Can anyone help me sort this out? The error message which I get is "UserId and RoleId are required."
/* This is the AssignRole View */
@model Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole
@{
ViewBag.Title = "AssignRole";
}
AssignRole
@using (Html.BeginForm())
{
Assign Roles
@Html.LabelFor(model => model.UserId, "User Name", new { @class = "col-md-2 control-label" })
@Html.DropDownList("AllUsers", null, "Select a User", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.RoleId, "Role Type", new { @class = "col-md-2 control-label" })
@Html.DropDownList("AllRoles", null, "Select a Role", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.RoleId, "", new { @class = "text-danger" })
}
@Html.ActionLink("Back to List", "Index")
/* This is Roles Controller */
// Assign roles
public ActionResult AssignRole()
{
ViewBag.AllUsers = new SelectList(db.Users, "Id", "UserName");
ViewBag.AllRoles = new SelectList(db.Roles, "Id", "Name");
return View();
}
[HttpPost]
public ActionResult AssignRole(IdentityUserRole userRole)
{
if (ModelState.IsValid)
{
db.UserRoles.Add(userRole);
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
Console.WriteLine(e);
}
return RedirectToAction("UsersWithRoles");
}
ViewBag.AllUsers = new SelectList(db.Users, "Id", "UserName",userRole.UserId);
ViewBag.AllRoles = new SelectList(db.Roles, "Id", "Name",userRole.RoleId);
return View(userRole);
}
Manura SilvaPosted Jun 24, 2019, 12:50 AM
Sivakumar KonetiPosted Jun 23, 2019, 11:58 PM
Manura SilvaPosted Jun 22, 2019, 9:59 AM
Afzaal Ahmad ZeeshanPosted Jun 22, 2019, 4:45 AM