Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDownListFor(...) selecting boolean false by default

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?

like image 823
StartingFromScratch Avatar asked Oct 06 '11 15:10

StartingFromScratch


1 Answers

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)
like image 84
JoshYates1980 Avatar answered Oct 18 '22 14:10

JoshYates1980