bguler
bguler

Reputation: 247

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 ?

Upvotes: 7

Views: 4434

Answers (2)

Simon C
Simon C

Reputation: 9508

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" })

Upvotes: 5

Stephen King
Stephen King

Reputation: 836

Adding "checked" to the attribute list will make it checked no matter what. I would make sure the value in your model is either null or false.

Upvotes: 0

Related Questions