Reputation: 690
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.
Upvotes: 1
Views: 2743
Reputation: 690
I did it by replacing RadiobuttonFor with RadioButton:
<div class="row">
<label>@Html.LabelFor(model => model.IsActive)</label>
</div>
<div class="row col-md-12">
@Html.RadioButton("IsActive", true, false) Yes
@Html.RadioButton("IsActive", false, false) No
@Html.RadioButton("IsActive", null, true) All
</div>
Upvotes: 1
Reputation: 218892
You cannot pass NULL
as the value for the radio button when using RadioButtonFor
helper method. If you pass ""
as the value, you cannot set that in your GET action as your variable type is bool?
,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 name
attribute value matches your view model property name, model binding will work fine when you submit the form.
@using (Html.BeginForm("Search","Customer"))
{
<label>Active</label>
<input type="radio" name="IsActive" value="true"/>
<label>In Active</label>
<input type="radio" name="IsActive" value="false"/>
<label>All</label>
<input type="radio" name="IsActive" checked="checked" />
<input type="submit"/>
}
Here we are setting the checked
attribute 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 of CheckBoxFor
or RadioButtonFor
helper, 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.
Upvotes: 2