Don
Don

Reputation: 1572

@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

Upvotes: 8

Views: 10871

Answers (1)

aw04
aw04

Reputation: 11187

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.

Upvotes: 9

Related Questions