Amr Elgarhy
Amr Elgarhy

Reputation: 69022

How to set checked value for a radio input tag using ASP.Net?

I have this radio tag:

<input name="phoneRadio" class="phoneRadio" id="rbDefaultPhone" 
    type="radio" checked="<%# GetIsChecked(Eval("IsDefault")) %>"/>

in a repeater and GetIsChecked is a c# function which return bool value, my problem that its not affecting the checked value of the radio button the right way, Any one know how to fix that?

Upvotes: 5

Views: 7675

Answers (2)

Sangram Nandkhile
Sangram Nandkhile

Reputation: 18202

Bdukes's answer is correct. Before coming to this post, I spent lot of time in trying to figure out how to return checked=checked but

checked
checked=""
checked="checked"

are equivalent.

Considering 'IsDefault' returns bool,works well in all modern browsers.

<input name="phoneRadio" class="phoneRadio" id="rbDefaultPhone"  type="radio" 
 checked='<%#Eval("IsDefault")%>'

Check this for more explanation.

Upvotes: 0

bdukes
bdukes

Reputation: 156055

Just having the checked attribute on the input is enough to make it checked. In HTML, you just need to have checked in there, in XHTML, it should be checked="checked", but either way, you'll want to exclude the whole attribute if it isn't checked.

That is, GetIsChecked should (be renamed and) return either "checked='checked'" or String.Empty. You will then call it just in the input tag itself, not as the value for the checked attribute (which you should remove). It'll look something like this:

<input name="phoneRadio" class="phoneRadio" id="rbDefaultPhone" type="radio" <%# GetChecked(Eval("IsDefault"))%> />

 

protected string GetChecked(object isDefault)
{
    return (bool)isDefault ? "checked='checked'" : string.Empty;
}

Upvotes: 9

Related Questions