I have typical YesNo kind of dropdown in the application. For that, I have developed model (rather ViewModel Utility) class for future extension prupose.
public string Text { get; set; } // represents text part
public bool Value { get; set; } // represent value
public List<DropDown> DropDowns { get; set; } //list for binding
public void BuildYesNoDropDown()
{
DropDowns = new List<DropDown>();
DropDowns.Add(new DropDown { Text = "Yes", Value = true });
DropDowns.Add(new DropDown { Text = "No", Value = false });
}
Then, I bind it in view like following:
@Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.DropDowns, "Value", "Text",1),"Select") //last para - OptionLabel
On the view, all three parameters are getting display i.e. "Select", "Yes" and "No". But, by default "No" has been selected. If I make "Value" property as integer then it works fine and by default "Select" gets selected, but as mentioned in the code, if I tend to go with bool type then "No" gets selected.
How to get normal behavior when DataValueField is bool?
ViewModel
public bool flag { get; set; }
View
@Html.DropDownListFor(model => model.flag, new List<SelectListItem>()
{
new SelectListItem() { Text = "Yes", Value = "True" },
new SelectListItem() { Text = "No", Value = "False"}
}, "Select.....", new { @id = "flag", @class="form-control" })
@Html.ValidationMessageFor(model => model.flag)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With