简体   繁体   English

如何将自定义属性添加到 asp.net 下拉列表

[英]How to add custom attributes to asp.net dropdown list

I am trying to add a country name as country attribute to asp.net dropdown list control but i am not having any luck with it.我正在尝试将国家名称作为国家属性添加到 asp.net 下拉列表控件,但我没有任何运气。

ListItem newState;
foreach (DataRow drow in dsDist.Tables(1).Rows)
{
    newState = new ListItem(drow("statename").ToString(), drow("state").ToString());
    newState.Attributes.Add("country", drow("country-name").ToString());
    ddlstates.Items.Add(newState);
}

ddlstates.Items.Insert(0, new ListItem("", ""));
ddlstates.SelectedIndex = 0;

After Page Render;页面渲染后;

<select name="ddlStates" id="ddlStates" class="chosen-select-states" data-placeholder="search by state name" style="display: none;">
        <option selected="selected" value=""></option>
        <option value="AK">Alaska</option>
        <option value="AL">Alabama</option>
        <option value="AR">Arkansas</option>
        <option value="AZ">Arizona</option>
</select>

This is what i am expecting;这就是我所期待的;

<option country="usa" value="AK">Alaska</option>
<option country="canada" value="ON">Ontario</option>

Your attributes should be visible on the rendered page with your browser's developer tools.使用浏览器的开发人员工具,您的属性应该在呈现的页面上可见。 But, attributes won't be posted back and you won't be able to get them back on the SelectedIndexChanged event for example.但是,属性不会被回发,并且您将无法在SelectedIndexChanged事件中恢复它们。

You have to create your own custom control derived from DropDownList or to store those attributes elsewhere.您必须创建自己的从 DropDownList 派生的自定义控件或将这些属性存储在其他地方。

Depending on what you want to do, you could perhaps store a Dictionary<String,String> itemAttributes containing ListItems values and attributes.根据您想要执行的操作,您或许可以存储包含 ListItems 值和属性的Dictionary<String,String> itemAttributes

This could something as:这可能是:

Dictionary<string, string> itemAttributes = new Dictionary<string, string>();
            ListItem newState;

            foreach (DataRow drow in dsDist.Tables(1).Rows)
            {
                newState = new ListItem(drow("statename").ToString(), drow("state").ToString());
                //newState.Attributes.Add("country", drow("country-name").ToString());

                ddlstates.Items.Add(newState);
                itemAttributes.Add(drow("state"), drow("country-name"));
            }

            ddlstates.Items.Insert(0, new ListItem("", ""));
            ddlstates.SelectedIndex = 0;

            Session["Attributes"] = itemAttributes;
            ViewState["Attributes"] = itemAttributes;

Beware of the size of the session or viewstate if you use this method.如果使用此方法,请注意 session 或视图状态的大小。

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

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