RadioButton comes checked automatically
Asked Answered
C

2

7

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 ?

Carmagnole answered 20/6, 2013 at 19:39 Comment(3)
What value does the property in the model have? If it's true then I'm pretty sure that that will override the @checked = "false"Hortensiahorter
@Hortensiahorter it have just text. and checked="false" stands in properties but it has no effect.Carmagnole
can you update the question to include the model classArda
F
5

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" })
Fennie answered 20/6, 2013 at 22:6 Comment(0)
B
0

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.

Ballista answered 20/6, 2013 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.