MVC 3 从视图、模型中检索复选框值

MVC 3 Retrieve checkbox values from View, Model

也许(实际上我确定)是我,但我似乎无法弄清楚如何检索列表项作为模型对象的一部分。 post here 似乎让每个人都满意,但在我有限的理解中,这两个答案都不相关。 我需要获取已检查的项目,以便更新 Db。听起来很简单。

我的模特:

    public class UserAdminModel
{
    public Guid UserId { get; set; }
    public string UserName { get; set; }
    public List<UserRole> UserRoles { get; set; }
    public string csvAllRolls { get; set; }
}

public class UserRole
{
    public Guid RoleId { get; set; }
    public string UserRoleName { get; set; }
    public bool UserisinRole  { get; set; }
}

我的看法:

<% using (Html.BeginForm("UpdateRoles", "UserAdmin", FormMethod.Post))
{%>

<input type="hidden" id="UserId" name="UserId" value="<%: Model.UserId %>" />
...

<%  foreach (var role in Model.UserRoles)
    {  %>
<tr>

    <td>&nbsp;</td>
    <td colspan="2" nowrap="nowrap"><%: role.UserRoleName %></td>
    <td>&nbsp;</td>
    <td>
        <input type="checkbox" id="UserRoles" name="UserRoles" value="<%: role.UserRoleName %>"
            <% if (role.UserisinRole) { %>                
             checked="checked"
            <% } %>
             /></td>
</tr>
<%  } %>
...
        <input type="submit" name="Submit" value="Update Roles" /></td>
<%  } %>

我的控制器:

        [HttpPost]
    public ActionResult UpdateAllRoles(UserAdminModel model)
    {
        Guid uid = new Guid( Request["UserId"]);


        return RedirectToAction("Index", "MyController");
    }

UserId 顺利通过,但模型的其余部分为空。任何帮助将不胜感激。

您需要使用 for 循环,以便您的表单控件具有正确的名称属性以绑定到您的模型(我会留给您从 razor 转换为 aspx)

@using (Html.BeginForm("UpdateRoles", "UserAdmin", FormMethod.Post))
{
  @Html.HiddenFor(m => m.UserId) // or add this as a route parameter in BeginForm()
  ...
  for(int i = 0; i < Model.UserRoles.Count; i++)
  {
    @Html.HiddenFor(m => m.UserRoles[i].RoleId)
    @Html.CheckBoxFor(m => m.UserRoles[i].UserisinRole)
    @Html.LabelFor(m => m.UserRoles[i].UserisinRole, Model.UserRoles[i].UserRoleName)
  }
  <input type="submit" name="Submit" value="Update Roles" />
}

当您提交表单时,model.UserRoles 将包含所有角色,您可以使用

获取所选角色
var selectedRoles = model.UserRoles.Where(r => r.UserisinRole);

旁注:在这里使用 <table> 似乎不合适。