특정 역할이있는 사용자를 나열하는 강력한 형식의보기 (userController에 바인딩 됨)가 있으며 그 아래에 제출 단추가있는 모든 역할을 포함하는 드롭 다운 목록이 있습니다. . 필요한 것은 해당 사용자에게 새로운 역할을 할당하는 것입니다. ActionResult 메서드는 UserRolesController에 있습니다. ActionImaging 메서드에 대한 단추 클릭시 userId 및 RoleId를 전달할 수 있습니까? UserRolesController에서버튼에 매개 변수를 전달하면 강력한 형식의보기가 다른 컨트롤러에 전달됨
ActionResult 방법 :이 같은
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddRole(UserRole userRole, int roleId, int userId)
{
if (!ModelState.IsValid) return View(userRole);
var check = db.UserRoles.Any(x => x.RoleID == roleId && x.UserID == userId);
if (check)
ViewBag.ResultMessage = "This user already has the role specified !";
else
db.UserRoles.Add(userRole);
db.SaveChanges();
ViewBag.ResultMessage = "User added to the role succesfully !";
return RedirectToAction("Index");
}
보기 :
@model IEnumerable<MvcAppCRUD.user>
@{
ViewBag.title = "AssignRole";
}
<h2>Assign Role</h2>
@if (!Model.Any())
{
@Html.Label("No Roles assigned for this user")
}
else
{
<table>
<tr>
<th>
@Html.DisplayName("Email")
</th>
<th>
@Html.DisplayName("Role Name")
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.email)
</td>
<td>
@Html.DisplayFor(modelItem => item.RoleName)
</td>
<td>
@Html.ActionLink("Delete", "Delete", new {id = item.id})
</td>
</tr>
}
</table>
}
<hr />
<div class="display-label">
@Html.DisplayName("Add Role")
</div>
<div class="display-field">
@Html.DropDownList("Roles", (SelectList) ViewBag.Roles)
</div>
@using (Html.BeginForm("AddRole", "UserRoles"))
{
<div class="message-success">@ViewBag.ResultMessage</div>
}
<p>
<input type="submit" value="Assign" />
</p>
<p>
@Html.ActionLink("Back to List", "Index")
</p>
모델 엔티티 :
public partial class UserRole
{
public int ID { get; set; }
public int UserID { get; set; }
public int RoleID { get; set; }
public int Status { get; set; }
public virtual user Users { get; set; }
public virtual Role Roles { get; set; }
}
public partial class user
{
public user()
{
Roles = new List<SelectListItem>();
}
public long id { get; set; }
public string email { get; set; }
public string password { get; set; }
public System.DateTime reg_date { get; set; }
public byte validated { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
public int RoleId { get; set; }
public string RoleName { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
//public IEnumerable<Role> Roles { get; set; }
}
public partial class Role
{
public int ID { get; set; }
public string RoleName { get; set; }
public string Desc { get; set; }
public int Status { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
버튼에 아무런 변화가 없습니다 클릭합니다. 모델보기에서 다른보기로 매개 변수로 값을 전달할 수 있습니까?
모델 또는 GET 방법을 표시하지 않았습니다. 당신은'Roles'라는 속성을 포함하고 있습니까? 모델 속성과'ViewBag' 속성에 같은 이름을 부여해서는 안됩니다. –
당신은 또한 모델에 IEnumerable을 전달합니다. 그러나 한 명의 사용자 만 (하나는?) 다시 전달할 것으로 예상하고, 사용자가 제어 할 수있는 컨트롤이 없으므로 어쨌든 아무 것도 게시하지 않습니다. –
코드를 업데이트했습니다. 예 사용자 모델에서 Roles 속성을 선언했습니다. – naeemmalik