15

I have something like the following in an ASP.NET MVC application:

IEnumerable<string> list = GetTheValues();
var selectList = new SelectList(list, "SelectedValue");

And even thought the selected value is defined, it is not being selected on the view. I have this feeling I'm missing something here, so if anyone can put me out my misery!

I know I can use an annoymous type to supply the key and value, but I would rather not add the additional code if I didn't have to.

EDIT: This problem has been fixed by ASP.NET MVC RTM.

Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
Chris Canal
  • 4,824
  • 9
  • 35
  • 45
  • 1
    See my DDL tutorials http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc and http://blogs.msdn.com/b/rickandy/archive/2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx – RickAndMSFT Feb 14 '12 at 19:21

4 Answers4

15

If you're just trying to to map an IEnumerable<string> to SelectList you can do it inline like this:

new SelectList(MyIEnumerablesStrings.Select(x=>new KeyValuePair<string,string>(x,x)), "Key", "Value");
Alex
  • 9,250
  • 11
  • 70
  • 81
14

Try this instead:

IDictionary<string,string> list = GetTheValues();
var selectList = new SelectList(list, "Key", "Value", "SelectedValue");

SelectList (at least in Preview 5) is not clever enough to see that elements of IEnumerable are value type and so it should use the item for both value and text. Instead it sets the value of each item to "null" or something like that. That's why the selected value has no effect.

Tim Scott
  • 15,106
  • 9
  • 65
  • 79
4

Take a look at this: ASP.NET MVC SelectList selectedValue Gotcha

This is as good explanation of what is going on as any.

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
KP.
  • 2,138
  • 23
  • 21
2

Try this

ViewBag.Items = list.Select(x => new SelectListItem() 
                              {
                                  Text = x.ToString()
                              });
Jay Sheth
  • 21
  • 1