在继承的ASP上使用Javascript清除选定项失败.净RadioButtonList

Fail to clear selected item with Javascript on inherited ASP.Net RadioButtonList

本文关键字:失败 RadioButtonList 清除 Javascript 继承 ASP      更新时间:2023-09-26

我需要从自定义的RadioButtonList中清除选中的项目,但它不能在回发。

我有一个从ASP继承的自定义控件。净RadioButtonList。当控件具有初始选定值时,如果我调用客户端函数来清除选定的项,然后执行回发,则初始选定的项将被重新选中。

如果我使用ASP。Net RadioButtonList,在回发时,被选中的项被清除,因此可以工作,但是简单地继承内置的类会失败

简写:

<div>    
<a href="javascript:Clear()">Clear</a>
</div>
<h1>
    <asp:Label Text="ready..." runat="server" ID="lblTest" /></h1>
<script type="text/javascript">
    function ChangeValue() {
        var obj = document.getElementById('test_1');
        obj.checked = true;
    }
    function Clear() {
        var obj = document.getElementById('test_0');
        obj.checked = false;
        obj = document.getElementById('test_1');
        obj.checked = false;
    }
</script>
<asp:Button ID="button" runat="server" onclick="button_Click" />

后面的代码

public class MyRadio : RadioButtonList
{
}
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    MyRadio test = new MyRadio();
    test.ID = "test";
    test.Items.Add(new ListItem("First", "First"));
    test.Items.Add(new ListItem("Second", "Second"));
    if (!Page.IsPostBack)
        test.SelectedValue = "Second"; 
    this.Form.Controls.Add(test);        
}
protected void button_Click(object sender, EventArgs e)
{
    RadioButtonList rl = this.FindControl("test") as RadioButtonList;
    if (rl.SelectedItem == null)
        lblTest.Text = "No selected item";
    else
        lblTest.Text = rl.SelectedItem.Value + " - " + rl.SelectedItem.Text;
}

如果我将"test"更改为RadioButtonList,然后在页面中单击clear,然后发布回来,我看到文本"没有选择的项目",这是我需要的;

解决方案是在派生类中实现IPostBackDataHandler。从一个在MSDN上找到它的朋友那里得到的

public class MyRadio : RadioButtonList, System.Web.UI.IPostBackDataHandler
{
bool System.Web.UI.IPostBackDataHandler.LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
{
    foreach (ListItem item in this.Items)
    {
        item.Selected = false;
    }
    return this.LoadPostData(postDataKey, postCollection);
}
void System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent()
{
    this.RaisePostDataChangedEvent();
}
protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    Page.RegisterRequiresPostBack(this);
}
}