I have a MVC View Model in which I have nullable boolean property:
[DisplayName("Is Active")]
public bool? IsActive { get; set; }
View:
<div class="col-md-3">
<div class="row">
<label>@Html.LabelFor(model => model.IsActive)</label>
</div>
@Html.RadioButtonFor(model => model.IsActive, true, new {id = "IsIsActiveTrue" })
<label>Yes</label>
@Html.RadioButtonFor(model => model.IsActive, false, new {id = "IsIsActiveFalse" })
<label>No</label>
@Html.RadioButtonFor(model => model.IsActive, "", new {id = "IsIsActiveAll"})
<label>All</label>
</div>
By default, I would like to select All when page loads. I tried to add
@checked = "checked"
but it didn't work (any of radiobutton value is selected). Please advise.
You cannot pass
NULLas the value for the radio button when usingRadioButtonForhelper method. If you pass""as the value, you cannot set that in your GET action as your variable type isbool?,not string.If you absolutely want 3 radiobuttons with your current type, you may simply write pure HTML code to render that. As long as your radio button's
nameattribute value matches your view model property name, model binding will work fine when you submit the form.Here we are setting the
checkedattribute for all in the HTML markup.Another option is to switch your controls from 3 radio buttons to 2 checkboxes. You can mark all of them checked initially and user may select/unselect as needed. Another option is changing your type from
bool?to an enum with these 3 values. With both of these approaches, with the use ofCheckBoxFororRadioButtonForhelper, you should be able to set the items which needs to be checked, in your GET action method. Use the one which is more appropriate to your code structure/style.