Problem with ASP.Net MVC SelectLIst and List

后端 未结 1 1883
北海茫月
北海茫月 2020-12-08 15:32

I\'m extending an Enum and, given the following code, selectListItems is a generic List of SelectListItems that has all the correct values for my Enum.

相关标签:
1条回答
  • 2020-12-08 15:55

    You need to change the line where you build it to tell it where to look for the values. In your case it would be:

    SelectList selectList = new SelectList(selectListItems, "Value", "Text");
    

    This will not carry over the selected item though. In that case you will need figure out which item should be the selected one and pass it's value in via the forth param.

    Here is an example:

    List<SelectListItem> items = new List<SelectListItem>();
    items.Add(new SelectListItem() { Text = "Test1", Value = "1", Selected = false });
    items.Add(new SelectListItem() { Text = "Test8", Value = "8", Selected = true });
    items.Add(new SelectListItem() { Text = "Test3", Value = "3", Selected = false });
    items.Add(new SelectListItem() { Text = "Test5", Value = "5", Selected = false });
    
    SelectList sl = new SelectList(items, "Value", "Text", "8");
    

    You might also want to check out this SO thread that might be helpful.

    Edit: Just saw your comment, and it doesn't work because it isn't smart enough to know to look for the Text and Value fields by default. You could pass it an type of objects and it gives you the ability to bind to it by defining which properties to map to the Text and Value properties.

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