IEnumerable to SelectList, no value is selected

后端 未结 4 970
囚心锁ツ
囚心锁ツ 2020-12-31 06:05

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

IEnumerable list = GetTheValues();
var selectList = new SelectList(list, \"S         


        
相关标签:
4条回答
  • 2020-12-31 06:19

    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");
    
    0 讨论(0)
  • 2020-12-31 06:20

    Try this

    ViewBag.Items = list.Select(x => new SelectListItem() 
                                  {
                                      Text = x.ToString()
                                  });
    
    0 讨论(0)
  • 2020-12-31 06:25

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

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

    0 讨论(0)
  • 2020-12-31 06:35

    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.

    0 讨论(0)
提交回复
热议问题