Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Drop Down list not selectng selected item

I have a C#.Net MVC3 web app. I am using Drop Down lists all over the place and having success. However, there are two that I am having trouble with. The only difference is that I am creating the SelectLists on the fly in the code rather than using Lookup tables. I use lookup tables for all the other Drop Downs. When I QuickWatch the SelectLists in the code, the correct Item has the Selected property value set to true. However, when the page loads, the item with the Selected property is not displayed. The first item is. Any ideas? This is one of those werid ones. I've tried both ways below. In both cases, the ViewBag.DateToYear and the SelectList DateToYear have the right values and 'Selected' properties set

1)

//Controller

        IList<string> dateToYear = new List<string>();
        for (int i = 0; i < numberYears; i++)
        {
            dateToYear.Add(DateTime.Now.AddYears(i).Year.ToString());
        }
        ViewBag.DateToYear = new SelectList(dateToYear,"2014")

//View

        @Html.DropDownList("DateFromYear", (SelectList)ViewBag.DateToYear )

2) //Controller SAME as above

//View

List<SelectListItem> DateToYear = new List<SelectListItem>();
foreach (var m in ViewBag.DateToYear)
{
    DateToYear.Add(new SelectListItem { Selected = @m.Selected, Value = @m.Text, Text = @m.Text });
} 

@Html.DropDownList("DateFromYear", DateToYear)
like image 390
MikeTWebb Avatar asked Nov 16 '11 21:11

MikeTWebb


1 Answers

The problem is, SelectList works as designed. The bug is in the design. You may set the Selected Property in SelctedItem, but this will completely be ignored, if you traverse the list with the GetEnumerator() ( or if Mvc does that for you). Mvc will create new SelectfListItems instead.

You have to use the SelectList ctor with the SelectListItem[], the Text-Name, the Value-Name and the SelectedValue. Be aware to pass as SelectedValue the VALUE of SelectListItem, which you want to be selected, not the SelectListItem itself! Example:

Why not just do in the controller ?

Pseudo code :

//controller

ViewBag.DateToYear = new SelectList(new[]  
{ 
 new SelectListItem { Text = "10", Value = "10" }, 
 new SelectListItem { Text = "15", Value = "15" } 
 new SelectListItem { Text = "25", Value = "25" }, 
 new SelectListItem { Text = "50", Value = "50" }, 
 new SelectListItem { Text = "100", Value = "100" }, 
 new SelectListItem { Text = "1000", Value = "1000" }, 
}, "SomeText", "Value", "15");

The second option should be selected.

like image 145
Tomasz Jaskuλa Avatar answered Oct 01 '22 00:10

Tomasz Jaskuλa