我需要一个带有select元素的视图。我有以下VM类:
public class EditTicketVM
{
public EditTicketVM()
{
Statuses = new SelectList(new List<SelectListItem>{
new SelectListItem("Open", "open"),
new SelectListItem("Pending", "pending"),
new SelectListItem("Hold", "hold"),
new SelectListItem("Solved", "solved"),
new SelectListItem("Closed", "closed"),
});
}
public string Description { get; set; }
public string Subject { get; set; }
public string Status { get; set; }
public SelectList Statuses { get; set; }
}
并在页面上选择元素:
<select asp-for="Status" class="form-control" asp-items="Model.Statuses" />
但是在结果页面上,此元素为空:
我的代码有什么不正确?
答案 0 :(得分:5)
我已经对您的代码进行了测试。问题出在您的select
标记中。您正在使用自动关闭选择标签。这是行不通的。编写您的选择标签,如下所示:
<select asp-for="Status" class="form-control" asp-items="Model.Statuses">
<option value="">Select Status</option>
</select>
您在SelectList
初始化中也遇到了问题。您初始化SelectList
的方式无效。初始化您的SelectList
,如下所示:
public EditTicketVM()
{
Statuses = new SelectList(new List<SelectListItem> {
new SelectListItem(){Text = "Open", Value = "open"},
new SelectListItem(){Text = "Pending", Value = "pending"},
new SelectListItem(){Text = "Hold", Value = "hold"},
new SelectListItem(){Text = "Solved", Value = "solved"},
new SelectListItem(){Text = "Closed", Value = "closed"},
},"Value","Text");
}