0

I have a radio button that can started unchecked, but even when the condition is false, it's writting the checked attribute in html and the browser show checked

@Html.RadioButton("radio", "1", new { @checked = (condition) }) @Html.RadioButton("radio", "2", new { @checked = (condition) })

Deyvison Souto
  • 157
  • 1
  • 11
  • Because you have `@checked = (condition)`.Its the presence of the checked attribute that determines if a radio button is checked (`checked="checked"` or `checked="false"` or `checked="AnythingAtAll` all mean the the same thing - it will be checked –  Aug 15 '17 at 12:15
  • What are you wanting to do here. Its the value of your property `radio` that determines what is checked. If its `1` the first one will be selected an if its `2` the 2nd will be, otherwise none will be. What is the `type` and value or your property –  Aug 15 '17 at 12:16

3 Answers3

1

I think the proper use will be this

@Html.RadioButton("radio", "1",  (condition))

According to RadioButton , radio button constructor defined as

RadioButton(string name,Object value, bool isChecked)

which will produce

<!-- isChecked is true. --> 
<input type="radio" name="name" value="value" checked="checked" />
<!-- isChecked is false. --> 
<input type="radio" name="name" value="value" />

I think you are trying to use new htmlattribute which is not needed.

Munzer
  • 2,216
  • 2
  • 18
  • 25
0

The overload you are using for @Html.RadioButton takes HTML attributes. When you specify checked = (condition) you are specifying the attribute checked with a value.

With HTML inputs it's not a case of setting the checked value to true or false. The very presence of the checked attribute means the control is checked. So just checked, or checked = "", and even checked = "false" will all result in a checked control.

See also this related question: What's the proper value for a checked attribute of an HTML checkbox?

In your case you would be better off with the overload HtmlHelper.RadioButton Method (String, Object, Boolean) which lets you specify a boolean value for whether of not the control is checked.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
0

Just check your condition on the controller and supply boolean via ViewBag

@Html.RadioButton("TestButton", "Value", (Boolean)ViewBag.DefaultValue)

Ravi Kukreja
  • 627
  • 1
  • 8
  • 17