简体   繁体   English

C# 修改下拉列表中的项目

[英]C# Modify items in drop down list

My application currently uses Membership and Roles in a WebForms app with FormAuthentication.我的应用程序当前在带有 FormAuthentication 的 WebForms 应用程序中使用成员资格和角色。

My current roles are:我目前的角色是:
Admin行政
Guest来宾
Users用户

Some users were made but never got a role assigned as it was done directly in the database (before I understand how Membership and Roles worked).一些用户已创建但从未分配过角色,因为它是直接在数据库中完成的(在我了解成员资格和角色如何工作之前)。

All users are that have a role assigned are "Users".所有分配了角色的用户都是“用户”。 All Admin's have both an "Admin" role and a "Users" role in the UsersInRoles table in the database.在数据库的 UsersInRoles 表中,所有管理员都具有“管理员”角色和“用户”角色。

The code that follows is after I have clicked on a user from a user list datagrid on a different page.下面的代码是在我从不同页面上的用户列表数据网格中单击用户之后。 The username is passed via url parameter.用户名通过 url 参数传递。

I have the following code:我有以下代码:

public partial class editUser : System.Web.UI.Page
    {
        public MembershipUser usr;
        string[] rolesArray;
        public string roleChoice;

        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (Request.QueryString["username"] != null)
            {
                usr = Membership.GetUser(Request.QueryString["username"]);
            } else
            {
                // no user passed, so default to current user
                usr = Membership.GetUser(User.Identity.Name);  
            }

            if (!Page.IsPostBack)
            {

                // Get the list of roles and populate dropdown
                rolesArray = System.Web.Security.Roles.GetAllRoles();

                RoleDDL.DataSource = rolesArray;
                // add a "None" role to anyone that doesn't have a role assigned yet
                RoleDDL.Items.Insert(0, new ListItem("None"));
                // do not allow a user to be assigned the "Guest" role.
                RoleDDL.Items.Remove("Guest");
                RoleDDL.DataBind();

                // Set current email on page load for the user.  If username was passed then that user, otherwise the user that is logged in as an Admin
                EmailTextBox.Text = usr.Email;
                IsLockedOutCheckbox.Checked = usr.IsLockedOut;
                IsApprovedCheckbox.Checked = usr.IsApproved;

                // If the user is not locked out, disable the checkbox because you cannot set the checkbox programatically
                if (IsLockedOutCheckbox.Checked == false) 
                {
                    IsLockedOutCheckbox.Enabled = false;
                }

                // Select current role for user
                string[] currentUserRoles = System.Web.Security.Roles.GetRolesForUser(usr.UserName);
                // Choose the current user role from currentUserRoles and assign to DDL.  Always choose Admin if it exists, User only if Admin doesn't exist, and None if no roles.
                foreach (string value in currentUserRoles) {
                    if (System.Web.Security.Roles.IsUserInRole(usr.UserName, "Admin")) 
                    {
                        RoleDDL.SelectedValue = "Admin";
                        break;  // "Admin" users are also "Users" users so break out of the for loop.  Otherwise the drop down will select "Users".
                    }

                    if (System.Web.Security.Roles.IsUserInRole(usr.UserName, "Users"))
                    {
                        RoleDDL.SelectedValue = "Users";
                    }
                    else
                    {
                        RoleDDL.SelectedValue = "None";
                    }

                }
            }

        }
}

The drop down list after running my code is as follows:运行我的代码后的下拉列表如下:

Admin行政
Guest来宾
Users用户

My issues are:我的问题是:

  1. Removing "Guest" is failing and still shows in my drop down list.删除“来宾”失败,但仍显示在我的下拉列表中。
  2. I cannot get "None" to show up in my drop down list.我的下拉列表中无法显示“无”。

I want the user to only select None, Admin, or User.我希望用户仅 select 无、管理员或用户。
I won't let None be saved - this will give an error that a different role must be chosen.我不会让 None 被保存 - 这将给出一个必须选择不同角色的错误。
I will check if the current drop down selection matches the roles they are in.我将检查当前的下拉选择是否与他们所在的角色匹配。

If there is a change then:如果有变化,那么:
For Admin I will add the role for "Admin".对于管理员,我将为“管理员”添加角色。
For User I will check if they were an admin and RemoveRole("Admin") if they were.对于用户,我将检查他们是否是管理员和 RemoveRole("Admin") 如果他们是。
For users that do not have a role (currentUserRoles is null) i'll add a "Users" role.对于没有角色的用户(currentUserRoles 为空),我将添加一个“用户”角色。

I am using Guest as a role to browse the site as read-only.我使用 Guest 作为角色以只读方式浏览该站点。 I do not want this as a choice.我不希望这是一个选择。

Also most drop downs will have an key/item and value.此外,大多数下拉菜单都会有一个键/项目和值。 I've never assigned roles to a dropdown list, so am I only assigning the key/item when I do "RoleDDL.datasource = rolesArray"?我从未将角色分配给下拉列表,所以我是否只在执行“RoleDDL.datasource = rolesArray”时分配键/项目?

What am I doing wrong?我究竟做错了什么?

I think you could try to add None and also remove Guest in your rolesArray instead of doing it in the RoleDDL.我认为您可以尝试在角色数组中添加 None 并删除 Guest,而不是在 RoleDDL 中进行。 Because we can see that the modification that you are doing in the RoleDDL are not working as you were expecting it.因为我们可以看到您在 RoleDDL 中所做的修改没有像您预期的那样工作。

You could also try to "overwrite" the Guest role, because, if I understand correctly, all members with the Guest role should instead have the None role.您也可以尝试“覆盖”Guest 角色,因为如果我理解正确,所有具有 Guest 角色的成员都应该拥有 None 角色。 So if you change the Guest to stop showing Guest but instead show None, than you wouldn't have to change the behaviour of your database but only change the display.因此,如果您将 Guest 更改为停止显示 Guest 而是显示 None,那么您不必更改数据库的行为而只需更改显示。

According to MSDN , DataBind binds the DataSource to the control ( DropDownList in this case).根据MSDNDataBindDataSource绑定到控件(在本例中为DropDownList )。

This means that any prior data will be discarded and the data from DataSource will be copied in the control.这意味着任何先前的数据都将被丢弃,来自DataSource的数据将被复制到控件中。

In your case, the issue is that you call DropDownList.DataBind() after you insert and remove items.在您的情况下,问题是您在插入和删除项目后调用DropDownList.DataBind() To fix your issue, you need call DropDownList.DataBind() after changing the DropDownList.DataSource and call the Items.Insert and Items.Remove after the data has been bound.要解决您的问题,您需要在更改DropDownList.DataSource后调用DropDownList.DataBind()并在绑定数据后调用Items.InsertItems.Remove Both of these methods will do the binding on their own.这两种方法都将自己进行绑定。

// [...]
RoleDDL.DataSource = rolesArray;
// Bind the DataSource
RoleDDL.DataBind(); 
// Both of these will perform the binding on their own.
RoleDDL.Items.Insert(0, new ListItem("None"));
RoleDDL.Items.Remove("Guest");
// [...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM