TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Manura Silva
1.7k
25
1.4k
How to assign roles to users by a single user
Jun 22 2019 3:00 AM
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";
}
<h2>AssignRole</h2>
@using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Assign Roles</h4>
<hr />
<div class="form-group">
@Html.LabelFor(model => model.UserId, "User Name", new { @class = "col-md-2 control-label" }) <!--User name is label-->
<div class="col-md-10">
@Html.DropDownList("AllUsers", null, "Select a User", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.RoleId, "Role Type", new { @class = "col-md-2 control-label" })
<div class="col-md-10"> <!--Role Type is label-->
@Html.DropDownList("AllRoles", null, "Select a Role", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.RoleId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Assign" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
/* 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);
}
Reply
Answers (
4
)
Open Source University Management System in .NET MVC
How to filter records with multiple filters like listbox mvc