Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

c# - Problem with ASP.Net MVC SelectLIst and List<SelectListItems>

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.

The first foreach loop works fine. However, when I create the actual SelectList and pass in selectListItems, all the values are lost. How can I keep those values intact?

foreach (SelectListItem item in selectListItems)
{
    string tex = item.Text;
    string val = item.Value;
    string sel = item.Selected.ToString();
}

SelectList selectList = new SelectList(selectListItems);

foreach (SelectListItem slid in selectList)
{
    string tex = slid.Text;
    string val = slid.Value;
    string sel = slid.Selected.ToString();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...