DropDownList の ListItems 属性はポストバック時に失われますか? 質問する

DropDownList の ListItems 属性はポストバック時に失われますか? 質問する

同僚がこれを見せてくれました:

Web ページには 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;
    }

ページの読み込み時にアイテムのツールチップが表示されますが、最初のポストバックで属性が失われます。なぜこのようなことが起こるのでしょうか。また、回避策はありますか。

ベストアンサー1

私も同じ問題を抱えていたので貢献したいと思いましたこれ作者が継承された 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];
            }
        }
    }
}

おすすめ記事