【问题标题】:MVC3 List of Checkboxes for Role ManagementMVC3 角色管理复选框列表
【发布时间】:2012-01-25 15:42:50
【问题描述】:

我正在尝试管理 MVC3 应用程序中的角色。这个想法是我有一个用户列表,当我单击该行上的“编辑角色”按钮时,我会看到一个模式窗口,其中列出了所有可能的角色以及用户所属的角色。

然后我可以选择新角色并单击保存并将 ajax 帖子发送回服务器以保留更改。

我弹出了模式,但我不确定如何生成复选框,以便在更改时轻松提交回服务器。我想要最简单的解决方案。

这是我在单击“编辑角色”时填充模式的部分视图:

public ActionResult ChooseRolePartial(string username)
    {
        var userRoles = Roles.GetRolesForUser(username);
        var list = new MultiSelectList(Roles.GetAllRoles());
        foreach (var item in list)
        {
            item.Selected = userRoles.Contains(item.Value);
        }

        var model = new ChooseRoleModel
        {
             Roles = list,
             Username = username
        };

        return PartialView("Partials/ChooseRolePartial", model);
    }

我希望 MultiSelectList 有一个 EditorFor,它会为我处理。但情况似乎并非如此。它只是将我的每个角色的文本呈现为 false。

生成此复选框列表并将检查的内容与用户名一起提交回服务器的最佳方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc-3


    【解决方案1】:

    型号:

    public class ChooseRoleModel
    {
        public SelectListItem[] Roles { get; set; }
        public string Username { get; set; }
    }
    

    控制器:

    public class RolesController : Controller
    {
        ...
    
        public ActionResult ChooseRolePartial(string username)
        {
            var userRoles = Roles.GetRolesForUser(username);
            var roles = Roles.GetAllRoles().Select(x => new SelectListItem
            {
                Value = x,
                Text = x,
                Selected = userRoles.Contains(x)
            }).ToArray();
    
            var model = new ChooseRoleModel
            {
                Roles = roles,
                Username = username
            };
    
            return PartialView("Partials/ChooseRolePartial", model);
        }
    
        [HttpPost]
        public ActionResult ChooseRolePartial(ChooseRoleModel model)
        {
            ...
        }
    }
    

    查看:

    @model ChooseRoleModel
    
    @using (Html.BeginForm())
    {
        <div>
            @Html.LabelFor(x => x.Username)
            @Html.EditorFor(x => x.Username)
        </div>
        for (int i = 0; i < Model.Roles.Length; i++)
        {
            @Html.CheckBoxFor(x => x.Roles[i].Selected)    
            @Html.LabelFor(x => x.Roles[i].Selected, Model.Roles[i].Text)
            @Html.HiddenFor(x => x.Roles[i].Text)
        }
        <button type="submit">OK</button>
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      相关资源
      最近更新 更多