关于C#:无法在ASP.NET MVC中初始化SelectList

Unable to initialize SelectList in ASP.NET MVC

我正在努力使用ASP.NET MVC应用程序。目前,我正试图使一个复选框列表起作用。为了做到这一点,我使用了这篇博客文章。我觉得我接近了。但是,由于某些原因,我的所有复选框列表项都显示System.Web.Mvc.SelectListItem。我不懂为什么。我的模型代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public SelectList AvailableTypeList { get; set; }
public IEnumerable<string> SelectedTypes { get; set; }

public void Initialize()
{
  List<SelectListItem> items = new List<SelectListItem>();
  foreach (var availableType in await AvailableType.LoadFromDatabaseAsync())
  {
    SelectListItem listItem = new SelectListItem
    {
      Text = availableType.Name,
      Value = availableType.Id.ToString()
    };
    items.Add(listItem);
  }
  AvailableTypeList = new SelectList(items);

  int i = 0;
}

我有两个断点。一组位于表示items.Add(listItem)的行,另一组位于int i = 0;的行。

当第一个断点跳闸时,TextValue属性正是我所期望的。但是,当第二个断点跳闸时,我在监视窗口中注意到AvailableTypeList .FirstOrDefault().Text是" System.Web.Mvc.SelectListItem"。为什么?

我不明白为什么要重置SelectListItem对象的TextValue属性。我究竟做错了什么?


I notice in the watch window that AvailableTypeList
.FirstOrDefault().Text is"System.Web.Mvc.SelectListItem". Why?

在这里,

1
2
3
4
5
SelectListItem listItem = new SelectListItem
{
  Text = availableType.Name,
  Value = availableType.Id.ToString()
};

公共SelectList(
IEnumerable项目,
字符串dataValueField,
字符串dataTextField
)
您创建类型listItem的对象,然后在这里:

1
 items.Add(listItem);

您将其添加到SelectListItem objcets列表中。

另一方面,在以下行中:

1
AvailableTypeList = new SelectList(items);

使用这些项目创建一个新的SelectList对象。在SelectList中,列表中的项目将附加在SelectList中。由于项目中对象的类型是SelectListItem,因此这就是您创建的SelectList中项目的类型。

具体地说,您使用了SelectList的以下构造函数:

1
public SelectList(IEnumerable items)

如MSDN中所述的

Initializes a new instance of the SelectList class by using the
specified items for the list.

关于此:

I do not understand why the Text and Value properties of the
SelectListItem objects are being reset. What am I doing wrong? Thank
you SO much for any help you can provide.

之所以发生这种情况,是因为您没有使用正确的构造函数,如下所示:

1
2
3
4
5
public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField
)

您必须明确声明dataValueFielddataTextField。如果使用上面的方法,如下所示:

1
AvailableTypeList = new SelectList(items,"Value","Text");


使用以下项创建它:

1
SelectList docs = new SelectList(new[] { new SelectListItem { Text ="Please Select...", Value ="error", Selected = true } });

1
var list = new SelectList(Enumerable.Empty<SelectListItem>());