为用户,角色和角色映射创建所需的模型类。但是无法从View向用户分配角色。需要创建发布功能以更新特定用户的角色。这是下面的代码。
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>
}
无法编写正确的代码来更新列出的特定用户的正确配置文件。
非常感谢
答案 0 :(得分:0)
它得到解决,这要归功于我的朋友Aniket,它帮助我完成了调试过程,并且能够连接各个点。 这是有效的代码
[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");
}