为什么RadioButtonList属性PostBack丢失了?

时间:2013-10-28 00:56:05

标签: asp.net webforms

我在服务器端的RadioButtonList中添加属性“onclick”,但是当我点击按钮时

提交回发,属性丢失。

请帮我解决

这是我的示例代码

=== HTML ===

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:RadioButtonList ID="RadioButtonList1" runat="server"  
                    RepeatLayout="Flow" RepeatDirection="Horizontal" />
                <br />
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <br />
                <asp:Button ID="Button1" runat="server" Text="Button" />
        </form>
    </body>
</html>

======= ASP.NET ======

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];
            }
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        SetList();
        TextBox1.TextMode = TextBoxMode.Password;
        TextBox1.Attributes.Add("value", "123");
    }
}

void SetList() 
{
    List<ListItem> items = new List<ListItem>();
    items.Add(new ListItem { Text = "Yes", Value = "1" });
    items.Add(new ListItem { Text = "No", Value = "0" });

    RadioButtonList1.DataSource = items;
    RadioButtonList1.DataBind();

    for (int i = 0; i < RadioButtonList1.Items.Count; i++)
    {
        RadioButtonList1.Items[i].Attributes.Add("onclick", "Hello()");
    }  
}

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;
}

1 个答案:

答案 0 :(得分:1)

属性不会通过viewstate持久化。你必须做的工作是在每次回发时重新加载它们,或者自己使用viewstate或者通过其他一些机制(数据库,会话等)来保存它们。