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 ?
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> .
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.
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.
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" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With