Reputation: 119
Created required Model Class for Users, ROles and Role Mapping. But unable to assign Role to users from View. Need to create Post function to update Role for specific users. Here is below code.
public class Users
{
[Key]
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class RoleMaster
{
[Key]
public int ID { get; set; }
public string RollName { get; set; }
}
public class UserRolesMapping
{
[Key]
public int ID { get; set; }
public int UserID { get; set; }
public int RoleID { get; set; }
[ForeignKey("UserID")]
public virtual Users Users { get; set; }
[ForeignKey("RoleID")]
public virtual RoleMaster RoleMaster { get; set; }
}
public class Db :DbContext
{
public DbSet<Users> Users { get; set; }
public DbSet<RoleMaster> RoleMasters { get; set; }
public DbSet<UserRolesMapping> UserRolesMappings { get; set; }
}
[HttpGet]
public ActionResult RegisterRole()
{
using (Db db = new Db())
{
ViewBag.Name = new SelectList(db.RoleMasters.ToList(), "RollName", "RollName");
ViewBag.UserName = new SelectList(db.Users.ToList(), "UserName", "UserName");
return View();
}
}
@model EmpMVC.Models.Users
@{
ViewBag.Title = "RegisterRole";
}
<h2>RegisterRole</h2>
@using (Html.BeginForm("RegisterRole", "Users", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-group">
<label class="control-label col-md-2">Select UserName</label>
<div class="col-md-5">
@Html.DropDownList("UserName")
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Select Role</label>
<div class="col-md-5">
@Html.DropDownList("Name")
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<input type="submit" class="btn btn-primary" value="Register" />
</div>
</div>
}
Unable to write correct code to update correct profile for specific User listed.
Help much appreciated
Upvotes: 0
Views: 128
Reputation: 119
Got it resolved, thanks to my Friend Aniket on this, helped me with the Debugging process, and was able to connect the dots. Here is the code that works
[HttpPost]
public ActionResult RegisterRole(RoleMaster role, User user)
{
using (Db db = new Db())
{
UserRolesMapping dto = new UserRolesMapping();
User userDto = db.Users.FirstOrDefault(x => x.UserName == user.UserName);
dto.UserID = userDto.UserID;
RoleMaster roleDto = db.RoleMasters.FirstOrDefault(x => x.RollName == role.RollName);
dto.RoleID = roleDto.RoleID;
db.UserRolesMappings.Add(dto);
db.SaveChanges();
}
return RedirectToAction("Roles");
}
Upvotes: 0