Why is my SelectList populating with unwanted empty option selected

I am working on creating a view that contains a dropdown. To generate select list items, I wrote a method to return the list SelectListItem

needed for this drop down list - one of which has the Selected attribute set to true.

I have traced a method that generates IEnumerable<SelectListItem>

representing the parameters that I want to display and returns the desired result.

However, when I use Html.DropDownList()

using the return above IEnumerable<SelectListItem>

, my select displayable has an empty start option that does not display in the DOM. Choosing any option will remove it, but I am confused why the selected option from is List<SelectListItem>

not being executed.

A static method that generates a list SelectListItem

:

public static IEnumerable<SelectListItem> GetDropDownValues()
{
    IEnumerable<MyClass> myClassesForList = MyClass.GetItemsForList();
    List<SelectListItem> retVal = new List<SelectListItem>();
    retVal.Add(new SelectListItem() { Text = "Choose", Value = "0", Selected=true });

    IEnumerable<SelectListItem> myClassesSelectListItems =
        from x in myClassesForList
        select new SelectListItem
        {
            Text = x.Name,
            Value = x.Value
        };

    return retVal.Concat(myClassesSelectListItems);
}

      

Fragment of the Pantinent Razor:

@Html.DropDownList("dropDownVals", GetDropDownValues())

      

Edit 1 : Screenshot of the dropdown

Screenshot of resulting DropDownList

+3


source to share


1 answer


Make sure there is no name viewbag / viewdata dropDownVals

that contains a value that does not exist in the list returned by the methodGetDropDownValues

What if you use AddRange

instead Concat

:



retVal.Add(new SelectListItem() { Text = "Choose", Value = "0", Selected=true });
var myClassesSelectListItems = from x in myClassesForList
                               select new SelectListItem
                               {
                                   Text = x.Name,
                                   Value = x.Value
                               };

retVal.AddRange(myClassesSelectListItems);

return retVal;

      

0


source







All Articles