Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<string> to SelectList, no value is selected

Tags:

c#

asp.net-mvc

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.

like image 567
Chris Canal Avatar asked Oct 21 '08 16:10

Chris Canal


4 Answers

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.

like image 100
Tim Scott Avatar answered Oct 24 '22 00:10

Tim Scott


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");
like image 38
Alex Avatar answered Oct 24 '22 00:10

Alex


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

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

like image 24
KP. Avatar answered Oct 23 '22 23:10

KP.


Try this

ViewBag.Items = list.Select(x => new SelectListItem() 
                              {
                                  Text = x.ToString()
                              });
like image 40
Jay Sheth Avatar answered Oct 23 '22 23:10

Jay Sheth