简体   繁体   English

ASP.Net MVC SelectLIst和List的问题<SelectListItems>

[英]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. 我正在扩展一个Enum,并且给定以下代码, selectListItems是一个SelectListItems的通用List,它具有我的Enum的所有正确值。

The first foreach loop works fine. 第一个foreach循环工作正常。 However, when I create the actual SelectList and pass in selectListItems , all the values are lost. 但是,当我创建实际的SelectList并传入selectListItems ,所有值都将丢失。 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();
}

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. 您可能还想查看可能有用的SO线程

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. 编辑:刚刚看到你的评论,它不起作用,因为它不够聪明,知道默认情况下查找TextValue字段。 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. 您可以将它传递给一种对象,它通过定义要映射到TextValue属性的属性,使您能够绑定它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM