0

In my ViewModel i got two fields :

public AdTypeEnum Type { get; set; }
public IList<SelectListItem> TypeEnumList { get; set; }

That's how i fill the list :

public void SetLists()
{
    TypeEnumList = new List<SelectListItem>();
    TypeEnumList.Add(new SelectListItem { Value = "0", Text = "Select the type"});

    foreach (var en in Enum.GetValues(typeof(AdTypeEnum)).Cast<AdTypeEnum>())
    {
        TypeEnumList.Add(new SelectListItem 
        { 
            Value = ((int)en).ToString(), 
            Text = en.ToString(), 
            Selected = Type == (AdTypeEnum)en ? true : false
        });
    }
}

And then I'm just rendering a dropdown on my View :

@Html.DropDownListFor(x => x.Type, Model.TypeEnumList, new { @class = "form-control" })

But the selected value doesn't render and the first option is always selected. When I check the select in HTML I found that no one of the options got selected attribute, but when I debug my controller method I can see that always one of the selectListItem have the propety Selected=true. Why does it suddenly disappear when my view is rendering?

CSharpBeginner
  • 1,625
  • 5
  • 22
  • 36
  • You can try adding a default value: http://stackoverflow.com/questions/7229626/dropdownlistfor-default-value – jjh121 Jan 23 '16 at 23:30
  • What you mean? Im populating the List correctly, always one of the elements got Selected=true, but magically no one option on the view have the selected attribute :/ Thats what i want to figure out – CSharpBeginner Jan 23 '16 at 23:35
  • Your not populating the `SelectList` correctly. Do not add the first option (with `value="0')`) - you add the label option using the correct overload - `@Html.DropDownListFor(x => x.Type, Model.TypeEnumList, "Select the type", new { .. })` which generated a `null` value. And in the loop, it should be `Value = en.ToString(),` and finally, setting the `Selected` property of `SelectListItem` is pointless when binding to a property. Its the value of `Type` which determines which option is selected (the `Selected` property is ignored by the `DropDownListFor()` method –  Jan 27 '16 at 03:14

1 Answers1

0

Ok I already found out the result. I just had to change the Type from Enum into int and correctly populate it. Everything works! :)

CSharpBeginner
  • 1,625
  • 5
  • 22
  • 36