0
votes

I have been fumbling around with this problem the entire day, so I decided to ask for some help on here, and hopefully you can help.

I have the following in a view:

  @Html.DropDownListFor(model => model.IsProduction, new SelectList(new[]
   {
           new SelectListItem { Value = "", Text = "Select environment", Selected = true, Disabled = true },
           new SelectListItem { Value = "false", Text = "Test" },
           new SelectListItem { Value = "true", Text = "Production" }
   },
   "Value", "Text"),
   new { @class = "form-control", @id = "selectEnvironment" })

As you can see, this is a dropdown for a bool with 3 values within the dropdown. The first being what I want to be selected by default (although it is not), and then the values for "true" and "false".

The bool in the model is not nullable, and is not supposed to be nullable. The form will be unable to submit, as long as either "true" or "false" has not been selected.

My question here is: Can anyone see, why it would default to always selecting the "false"-value, although I have defined the ""-value selected by default?

I have tried it without the "Disabled"-attribute, and it changes nothing.

Thanks for any help, that you may be able to give :)

1

1 Answers

1
votes

Summary: This is an expected behavior of bool property which has default value of false.

I believe that you have IsProduction boolean property set like this:

[Required]
public bool IsProduction { get; set; }

Since this is non-nullable boolean property, the default value is set to false (see this reference), and any option contains false value will be selected by default when no value is assigned to the property, which overrides Selected property setting of SelectListItem instance.

If you change bool to Nullable<bool> (which you're not supposed to be), any option with Selected = true will be selected instead as shown in this fiddle because the default value for Nullable<bool> is null instead of false.

Also if you examine reference source, there are private methods named SelectInternal() and GetSelectListWithDefaultValue() which used to control behavior of DropDownListFor helper. This explains the reason why DropDownListFor with selected option placeholder must bind to bool? instead of bool.