2

我不知道我在搞砸什么。FormCollection似乎表明一切都是正确的。RoleName回来也很好。那为什么又RoleMembership回来了null

型号

public class EditRoleMembershipViewModel
{
    public string RoleName { get; set; }
    public Dictionary<string, bool> RoleMembership { get; set; }
}

控制器动作

[HttpGet]
public ActionResult EditRoleMembership(string roleName)
{
    var viewModel = new EditRoleMembershipViewModel {RoleName = roleName};

    var allUsers = _userServices.GetAllUsers();
    getRolesForUsers(allUsers);
    var role = _roleServices.GetRole(roleName);

    viewModel.RoleMembership = new Dictionary<string, bool>();
    foreach (var user in allUsers)
    {
        var isMember = user.Roles != null && user.Roles.Contains(role);
        viewModel.RoleMembership.Add(user.UserName, isMember);
    }

    return View(viewModel);
}

查看

@model CI.Portal.Mvc.ViewModels.EditRoleMembershipViewModel
@{
    ViewBag.Title = "Edit Role";
}
<h2>@ViewBag.Title: @Model.RoleName</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <table>
        <thead>
            <tr>
                <th>
                </th>
                <th>
                    In Role
                </th>
            </tr>
        </thead>
        <tbody>
            @{
                int index = 0;
                foreach (var item in Model.RoleMembership)
                {
                    <tr>
                        <td>
                            @item.Key
                            @Html.Hidden(string.Format("model.RoleMembership[{0}].Key", index), item.Key)
                        </td>
                        <td>@Html.CheckBox(string.Format("model.RoleMembership[{0}].Value", index), item.Value)</td>
                    </tr>
                    index++;
                }
            }
        </tbody>
    </table>

    <p>
        <input type="submit" value="Save" />
    </p>
}
<div>
    @Html.ActionLink("Back to Details", "RoleDetails", new { Model.RoleName })
</div>
4

1 回答 1

3

您能否尝试删除“模型”。复选框助手声明的前缀。

代替

<td>
    @item.Key
    @Html.Hidden(string.Format("model.RoleMembership[{0}].Key", index), item.Key)
</td>
<td>
    @Html.CheckBox(string.Format("model.RoleMembership[{0}].Value", index), item.Value)
</td>

做这个:

<td>
    @item.Key
    @Html.Hidden(string.Format("RoleMembership[{0}].Key", index), item.Key)
</td>
<td>
    @Html.CheckBox(string.Format("RoleMembership[{0}].Value", index), item.Value)
</td>
于 2012-07-16T17:32:36.257 回答