0

我在服务器端的 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;
}
4

1 回答 1

1

The attributes are not persisted via viewstate. You would have to do the work to reload them on every postback, or persist them using viewstate yourself, or via some other mechanism (database, session, etc.).

于 2013-10-28T01:03:47.610 回答