将按钮上的参数传递给强类型视图中的另一个控制器

时间:2014-12-01 22:16:29

标签: c# asp.net asp.net-mvc-4 razor

我有一个强类型视图(绑定到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; }
}

在按钮上单击没有任何反应。是否可以将值作为参数从一个模型视图传递到另一个模型视图?

1 个答案:

答案 0 :(得分:0)

您的代码存在许多问题。特别是你将IEnumerable<user>传递给模型不包括或在表单中呈现任何控件,所以没有回发任何内容,并且无论如何你都不能回发UserRole因为它的复杂对象和下拉列表只返回一个单一价值。并且没有必要在下拉列表中显示所有角色,然后检查它是否已在回发中被选中 - 只包括用户在创建视图时尚未拥有的角色。将消息分配给ViewBag然后重定向是没有意义的 - 它会立即丢失。

创建一个视图模型来表示您想要显示和编辑的内容(注意我已排除显示现有角色的属性)

public class UserRoleVM
{
  public int ID { get; set; } // user ID for post back
  public int Name { get; set; } // user name for display in the view
  [Display(Name="Select new role")]
  public int SelectedRole { get; set; }
  public SelectList RoleList { get; set; }
}

控制器

public ActionResult AddRole(int ID)
{
  UserRoleVM model = new UserRoleVM();
  var user = // Get the user based on the ID
  model.ID = ID;
  model.Name = user.??
  var roles = // Get all roles and remove those that the user already has
  model.RoleList = new SelectList(roles, "ID", "RoleName");
  return View(model);
}

查看

@model UserRoleVM
@using(Html.BeginForm())
{
  <h2>@Model.Name</h2> // users name
  @Html.LabelFor(m => m.SelectedRole)
  @Html.DropDownListFor(m => m.SelectedRole, Model.RoleList)
  <input type="submit" value="Add Role" />
}

发布方法

[HttpPost]
public ActionResult AddRole(UserRoleVM model)
{
  // model is now populated with the ID of the user and the ID of the selected role
  // save and redirect
}