显示动态复选框的现有选择

时间:2013-04-17 21:54:05

标签: c# javascript asp.net

我正在动态创建复选框,并希望显示现有选择或想要动态检查它们。这是创建复选框的代码

    private void Role()
    {
        SystemUserDal dal = new SystemUserDal();
        var roles = dal.GetRolesList();
        foreach (KeyValuePair<Guid, string> r in roles)
        {

            CheckBox chk = new CheckBox();
            chk.ID = r.Value;
            chk.Text = r.Value;
            rolepanel.Controls.Add(chk);
        }
    }

我有

      protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SystemUserDal dal = new SystemUserDal();
            var userID = Guid.Parse(Request.QueryString["ID"].ToString());
            var user = dal.getSystemUserByID(userID);
            if (user != null)
            {
                Role();
                var role = user.Roles;


                textuserid.Text = user.UserId.ToString();

user.Roles具有指定特定用户的所有角色。如何标记动态创建的复选框?

我试过这个但仍然工作,因为角色中有多个值

    private void Role(string role)
    {
        SystemUserDal dal = new SystemUserDal();
        var userId = Guid.Parse(Request.QueryString["ID"].ToString());
        var roles = dal.GetRolesList(userId);
        foreach (KeyValuePair<Guid, string> r in roles)
        {

            CheckBox chk = new CheckBox();
            chk.ID = r.Value;
            chk.Text = r.Value;
            if (role == r.Value)
            {
                chk.Checked = true;

            } rolepanel.Controls.Add(chk);
        }
    }

1 个答案:

答案 0 :(得分:0)

可能会重写您的Roles()功能

foreach (KeyValuePair<Guid, string> r in roles)
{

    CheckBox chk = new CheckBox();
    chk.ID = r.Value;
    chk.Text = r.Value;

    if(User.IsInRole(r.Value))
       chk.Checked = true;

    rolepanel.Controls.Add(chk);
}

更好的选择是使用<asp:CheckBoxList />控件

<asp:CheckBoxList ID="RolesList" runat="server">
</asp:CheckBoxList>

代码隐藏

for (int i = 0; i < RolesList.Items.Count; i++)
{
    if (User.IsInRole(RolesList.Items[i].Value))
       RolesList.Items[i].Selected = true;
}