Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RadioButton comes checked automatically

I used RadioButtonFor like this

@Html.RadioButtonFor(m => m.Content, Model.Content, new { @name = "rb", @class = "answer-radio", @id = "answer-" + Model.Counter,@checked = "false" })
    @Html.Label(Model.Content, new { @for = "answer-" + Model.Counter })
    @Html.HiddenFor(m => m.Content)

But this radiobutton comes "checked". How can i disable it ?

like image 807
bguler Avatar asked Jun 20 '13 19:06

bguler


People also ask

How do I make radio buttons not checked by default?

You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .

Do radio buttons need a default?

Always Offer a Default Selection One of the 10 heuristics of UI design says that users should be able to undo (and redo) their actions. This means enabling people to set a UI control back to its original state. In case of radio buttons this means that radio buttons should always have exactly one option pre-selected.

What is the difference between RadioButton and checkbox?

Checkboxes and radio buttons are elements for making selections. Checkboxes allow the user to choose items from a fixed number of alternatives, while radio buttons allow the user to choose exactly one item from a list of several predefined alternatives.


1 Answers

Are you sure you want a radio button? Seems like you might be after a Checkbox...

For a boolean, I would set up a 2 radiobuttons like so:

@Html.RadioButtonFor(m => m.Content, true, new { @id = "rb1" })
@Html.RadioButtonFor(m => m.Content, false, new { @id = "rb2" })

The html helper will figure out which one to check. If Model.Content is of another type, use different values for the radiobuttons and MVC will still figure out which one to check.

Edit:

Actually, it's even simpler than that. If the you use the Html helper RadioButtonFor method, it will check the radiobutton if it finds a value that matches the Model property. So you've specified your RadioButton as always having the same value as your Model property so it will always be checked (and that is the value that will be posted back in the form)

So, if you wanted a bool to default to false, and only return true if checked you could do just this:

@Html.RadioButtonFor(m => m.Content, true, new { @id = "rb1" })

where Content is originally set to false.

You can do it with other value types as well. e.g. if Content was a string, initially set to null, this would post back "RadioButtonChecked" only if the radio button was checked. Null otherwise:

@Html.RadioButtonFor(m => m.Content, "RadioButtonChecked", new { @id = "rb1" })
like image 84
Simon C Avatar answered Sep 20 '22 23:09

Simon C