加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – MVC3角色管理复选框列表

发布时间:2020-12-16 01:50:43 所属栏目:百科 来源:网络整理
导读:我正在尝试管理MVC3应用程序中的角色.我的想法是我有一个用户列表,当我点击行上的编辑角色按钮时,我得到一个模态窗口,其中包含所有可能角色的列表,其中用户是已检查的成员. 然后我可以选择新角色并单击“保存”并将ajax发送回服务器以保留更改. 我有模式弹出
我正在尝试管理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.

什么是生成此复选框列表的最佳方法,并将用户名和选中的内容提交回服务器?

解决方法

模型:

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,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>
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读