开发者

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>


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.


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.


Try making them get the attribute readonly="readonly" instead. A disabled input wont post a value.

http://www.w3schools.com/tags/att_input_readonly.asp


If elements disabled than they don't will be sent at postback. Before you do a postback you must enable them first. Example in jQuery:

 $('#<%= Button1.ClientID %>').click(function () { RadioButton1.disabled = false;
                                                   RadioButton2.disabled = false; });


Or when generating the disabled checkbox/radiobutton at server level, also generate an <input type='hidden'.. tag for the same name. That will post your value on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜