Asp.net

DropDownList 中的 ListItems 屬性在回發時失去?

  • August 21, 2009

一位同事給我看了這個:

他在網頁上有一個 DropDownList 和一個按鈕。這是後面的程式碼:

protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {
           ListItem item = new ListItem("1");
           item.Attributes.Add("title", "A");

           ListItem item2 = new ListItem("2");
           item2.Attributes.Add("title", "B");

           DropDownList1.Items.AddRange(new[] {item, item2});
           string s = DropDownList1.Items[0].Attributes["title"];
       }
   }

   protected void Button1_Click(object sender, EventArgs e)
   {
       DropDownList1.Visible = !DropDownList1.Visible;
   }

在頁面載入時,會顯示項目的工具提示,但在第一次回發時,屬性會失去。為什麼會出現這種情況,是否有任何解決方法?

我遇到了同樣的問題,想貢獻這個資源,作者創建了一個繼承的 ListItem Consumer 來將屬性持久保存到 ViewState。希望它可以節省我在偶然發現它之前浪費的時間。

protected override object SaveViewState()
{
   // create object array for Item count + 1
   object[] allStates = new object[this.Items.Count + 1];

   // the +1 is to hold the base info
   object baseState = base.SaveViewState();
   allStates[0] = baseState;

   Int32 i = 1;
   // now loop through and save each Style attribute for the List
   foreach (ListItem li in this.Items)
   {
       Int32 j = 0;
       string[][] attributes = new string[li.Attributes.Count][];
       foreach (string attribute in li.Attributes.Keys)
       {
           attributes[j++] = new string[] {attribute, li.Attributes[attribute]};
       }
       allStates[i++] = attributes;
   }
   return allStates;
}

protected override void LoadViewState(object savedState)
{
   if (savedState != null)
   {
       object[] myState = (object[])savedState;

       // restore base first
       if (myState[0] != null)
           base.LoadViewState(myState[0]);

       Int32 i = 1;
       foreach (ListItem li in this.Items)
       {
           // loop through and restore each style attribute
           foreach (string[] attribute in (string[][])myState[i++])
           {
               li.Attributes[attribute[0]] = attribute[1];
           }
       }
   }
}

引用自:https://stackoverflow.com/questions/1313447