Question

I'm using ASP.NET MVC3 I need to create a DropDownList with 4 values :

  • Don't mind
  • 0
  • 1
  • 2 or +

with "Don't mind" as selected item.

Here is my code :

public static IEnumerable<SelectListItem> ListAnimals()
    {
        List<SelectListItem> items = new List<SelectListItem>();

        items.Add(new SelectListItem { Text = "Don't mind", Value = "-1", Selected = true });
        items.Add(new SelectListItem { Text = "0", Value = "0" });
        items.Add(new SelectListItem { Text = "1", Value = "1" });
        items.Add(new SelectListItem { Text = "2 or +", Value = "2" });

        return items;
    }

and I use it like this in my view :

@Html.DropDownListFor(m => m.AnimalNumber, new SelectList(Animal.ListAnimals() , "Value", "Text"))

With this code, the selected item is always "0" whereas it should be "Don't mind" as I explicitly write it. BUT
when : items.Add(new SelectListItem { Text = "0", Value = "0" });
became : items.Add(new SelectListItem { Text = "0", Value = "[Anything but 0]" });
it perfectly works and "Don't mind" is correctly selected.

So, I think MVC automatically select item where Value = "0", in spite of the keyword Selected... How can I override it ? I really need to let Value = "0", and I'm sure we can override this behavior. Do someone know how ?

(BTW, I know my question is very close of this one but the answers given in this thread don't satisfy me. I don't want to write my DDL in HTML because I'll loose the binding between my value and my model, and writing a jQuery script to change the selected value is "a little bit hacky".)
Do any proper way exists ?

Was it helpful?

Solution

When you use the strongly-typed html helper for a DropDownList (Html.DropDownListFor), the Selected property of SelectListItem is overwritten by the value of your Model Property. It makes sense. So, when you use the Html Helper like below, the selected value will be Model.AnimalNumber. Since, the default value for an int is 0, when you create a new Model, and send it to your View, the value of its int properties are defaulted to 0. So, in this case, Model.AnimalNumber is 0, and therefore, the selected value of the DropDownList is the item with the value of 0.

@Html.DropDownListFor(m => m.AnimalNumber, Animal.ListAnimals())

In order to solve that issue, you can either change the type of your property to int? or you can make sure that the value of none of your SelectListItems is 0, or you can set a default value for your property (in this case AnimalNumber = -1).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top