【发布时间】:2014-12-01 22:16:29
【问题描述】:
我有一个强类型视图(绑定到 userController),它列出了具有特定角色的用户,下面我有一个下拉列表,其中包含所有角色和一个提交按钮。我只需要为该用户分配新角色。 ActionResult 方法在 UserRolesController 中。如何将按钮单击时的 userId 和 RoleId 传递给 ActionResult 方法。
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 属性。
-
我已将下拉列表绑定到角色实体。我可以从中获取 roleId。其他我需要 userId (id) 在我的情况下作为参数传递。
-
如何传回从 LINQ 查询中获得并在视图中列出的值?有什么建议吗?
标签: c# asp.net asp.net-mvc-4 razor