Keeping radio/checkbox values on postback?

2020-03-26 19:11发布

问题:

There's is something I don't get with ASP objects. I have a button in a update panel. On the same page, I have a checkbox, a radiobutton and a textbox (outside the update panel). When I click on my button, I access all those three objects. The textbox is able to keep the his text value. But the radio/checkbox always return false when I check there checked state.

Of course, my form is more complicated than what I just said. It involves Javascript and usercontrols. I managed to use the Request.Form to get the value of my checkbox/radio, but I don't find this solution to be neat enought.

Someone can help me to find why radio/check wont return there real checked state ? Thank you in advance!

Edit : I've tried to following in a simple aspx page and it seems to works :

 <asp:CheckBox runat="server" ID="checkbox" />

    <asp:RadioButton runat="server" ID="radio1" GroupName="radio" CssClass="testRadio" />
    <asp:RadioButton runat="server" ID="radio2" GroupName="radio" CssClass="testRadio" />

    <asp:TextBox runat="server" ID="text" />


    <asp:ScriptManager runat="server">
    </asp:ScriptManager>

    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:Button runat="server" ID="test_but" OnClick="test_click" />

        </ContentTemplate>
    </asp:UpdatePanel>

And then I can access all the properties into test_click(). So there is something in my real forms that breaks everything else. I've tried to add a little javascript into my test page, and it seems to works too.

回答1:

Known issue with these controls. Use the SaveViewState and LoadViewState methods to store and retrieve these values.

http://www.4guysfromrolla.com/articles/110205-1.aspx

protected override void LoadViewState(object savedState)
{
    base.LoadViewState(savedState);

    if (ViewState["Checked"] != null)
        checked = (bool)ViewState["Checked"];
}

protected override object SaveViewState()
{
    ViewState["Checked"] = checked;

    return base.SaveViewState();
}