我正在尝试在我的asp.net mvc应用程序中显示下拉列表。我在设置优先级中的列表项时遇到了困难。这里我的错误是什么?
public IList<SelectListItem> Priorities { get; set; }
Priorities = new List<SelectListItem>();
Priorities.Add(new IList<SelectListItem>
{
new SelectListItem { Text = "High", Value = "1"},
new SelectListItem { Text = "Low", Value = "0"}
});
@Html.DropDownListFor(m => m.SelectedPriority, Model.Priorities, "Select one")
答案 0 :(得分:1)
尝试更改
Priorities = new List<SelectListItem>();
通过
Priorities = new List<SelectListItem>() {
new SelectListItem { Text = "High", Value = "1"},
new SelectListItem { Text = "Low", Value = "0"}
};
或Cast和AddRange
((List<SelectListItem>)Priorities).AddRange(
new List<SelectListItem>() {
new SelectListItem { Text = "High", Value = "1"},
new SelectListItem { Text = "Low", Value = "0"}
}
);
使用IEnumerable的其他选项:
public IEnumerable<SelectListItem> Priorities { get; set; }
Priorities = new List<SelectListItem>();
Priorities = Priorities.Concat(new List<SelectListItem>() {
new SelectListItem { Text = "High", Value = "1"},
new SelectListItem { Text = "Low", Value = "0"}
}
);
答案 1 :(得分:1)
您无法在此处实例化界面:
Priorities.Add(new IList<SelectListItem>
{
new SelectListItem { Text = "High", Value = "1"},
new SelectListItem { Text = "Low", Value = "0"}
});
而是尝试将其实例化为实现IList的东西,并使用AddRangewhich用于这种情况:
Priorities.AddRange(new List<SelectListItem>
{
new SelectListItem { Text = "High", Value = "1"},
new SelectListItem { Text = "Low", Value = "0"}
});