我有一個強類型的視圖(綁定到userController)列出用戶特定的角色和下面,我有一個下拉列表包含所有提交按鈕的角色。我需要的只是爲該用戶分配新的角色。 ActionResult方法在UserRolesController中。如何將按鈕上的userId和RoleId傳遞給ActionResult方法。傳遞參數在按鈕點擊強類型視圖到另一個控制器
的ActionResult方法UserRolesController:
[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'屬性使用相同的名稱。 – 2014-12-01 22:29:33
您還將'IEnumerable傳遞給模型。但期望只傳回一個用戶(哪一個?),並且你沒有控制在你的內部,所以沒有任何事情會回來。 –
2014-12-01 22:34:57
我已經更新了代碼。是的,我已經在用戶模型中聲明瞭Roles屬性。 – naeemmalik 2014-12-01 22:35:55