ASP.NET - Access DropDownList item attribute in Code Behind

1

I have a DropDownList in which I add items as below:

var item= new ListItem("Texto do Item", "Valor do Item");
item.Attributes.Add("NomeAtributo", "ValorAtributo");

The DropDownList is rendered on the screen with the attribute, so far legal. When I select an item in DropDownList it triggers an event in code behind , where I want to get the value of the attribute again, however when I run the code below it comes null :

var meuAtributo = meuDropDownList.SelectedItem.Attributes["NomeAtributo"];

The Microsoft documentation is written in the description of WebControl.Attributes :

  

Gets the collection of arbitrary attributes (for rendering only)

Translation:

  

Pega a coleção de atributos arbitrários (somente para renderização).

How do I get the attribute value of this DropDownList in the OnSelectedIndexChanged event?

    
asked by anonymous 06.04.2017 / 20:43

1 answer

1

Actually the attributes only server to render the page, in the information retrieval these attributes are lost, but, there are ways to get around this, one would write the information in ViewState

Minimum example:

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) Load_Drop();
    }

    protected void Load_Drop()
    {
        var l1 = new ListItem("v1", "1");
        l1.Attributes.Add("a1", "r1");
        ViewState.Add("v1", "a1;r1");

        var l2 = new ListItem("v2", "2");
        l2.Attributes.Add("a2", "r2");
        ViewState.Add("v2", "a2;r2");

        DropDownList1.Items.Add(l1);
        DropDownList1.Items.Add(l2);            
        DropDownList1.DataBind();    

    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var drop = DropDownList1;
        int index = drop.SelectedIndex;
        if (index > -1)
        {
            ListItem item = drop.SelectedItem;
            string values = (string)ViewState[item.Text];                    
        }
    }
}

References

06.04.2017 / 22:22