Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Html.RadioButtonFor Default to Unchecked

In ASP.NET MVC4's Razor view, how to ensure none of the radio buttons default to unchecked? MVC seems to check one for me even I don't declare to check one in the following codes.

@Html.RadioButtonFor(model => model.test, true, new { id = "radio_test_True"}) Yes
@Html.RadioButtonFor(model => model.test, false, new { id = "radio_test_False"}) No

Thanks

like image 686
Don Avatar asked Feb 27 '14 23:02

Don


People also ask

How do I keep a radio button unchecked by default?

To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true . When set to true , the radio button becomes checked and all other radio buttons with the same name attribute become unchecked.

How to set default radio button in js?

None selected by default In case we need to select a radio button by default, we need to check it as true. Whenever the radio buttons are checked as true, then it will be autofocused by default.

How do I mark a radio button as checked?

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> .


1 Answers

Set Model.test to null in your controller or model constructor, and make sure it's nullable. A bool has to be either true or false, null will mean neither is checked.

public class WhateverTheModelIs
{
    public bool? test { get; set; }

    public WhateverTheModelIs()
    {
        test = null;
    }
}

Note: Setting the value to null is redundant as it is the default. I wanted to be explicit for the sake of the example.

like image 84
aw04 Avatar answered Sep 22 '22 00:09

aw04