Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabled radio button losing value after postback

I have two radio buttons that are disabled with javascript when the page loads. RadioButton1 is checked by default. When I click the button to do a postback, the RadioButton1 is no longer checked.

Anyone know why ?

Here's my code sample. The code behind is empty.

<asp:RadioButton ID="RadioButton1" runat="server"  GroupName="group" Checked="true"/>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="group" />
<asp:Button ID="Button1" runat="server" Text="Button"></asp:Button>
<script type="text/javascript">
    window.onload = function () {
        var RadioButton1 = document.getElementById('<%= RadioButton1.ClientID %>');
        var RadioButton2 = document.getElementById('<%= RadioButton2.ClientID %>');

        RadioButton1.disabled = true;
        RadioButton2.disabled = true;
    };
</script>
like image 312
Alexandre Pepin Avatar asked Feb 14 '11 22:02

Alexandre Pepin


2 Answers

This is behavior of HTML, not ASP.NET. Once you mark input element as disabled it is no longer posted in request. For text fields this can be avoided by using Readonly insted of Disabled but I think it doesn't work for checkboxes or radio buttons. If you still want to post the value you must send it in hidden field related to the radio button and process it manually on the server.

Edit:

Here you can read about disabled and readonly elements and about form submission:

Disabled control:

Disabled control cannot be sucessful.

Read-only control:

Read-only elements may be successful.

Form submission:

A successful control is valid for submission. Every successful control has its control name paired with its current value as part of submitted form data set. A successful control must be defined within a form element and must have a control name.

However:

  • Controls that are disabled cannot be successful.
like image 107
Ladislav Mrnka Avatar answered Nov 19 '22 07:11

Ladislav Mrnka


That's because disabled <input> elements don't send any value to the server on postback, and radio buttons don't store their checked state in ViewState, so it can't be persisted that way either.

Since both RadioButton1 and RadioButton2 are disabled, their name (group) won't be part of the postback, and ASP.NET will clear them both as a result.

like image 4
Frédéric Hamidi Avatar answered Nov 19 '22 08:11

Frédéric Hamidi