我正在将.Net Core Razor Pages与ADO.Net一起使用。我正在尝试从数据库中提取数据并插入到下拉列表中。我得到这个
无法将类型'System.Collections.Generic.List
'隐式转换为'System.Collections.Generic.IEnumerable '。存在显式转换(您是否缺少演员表?)
CommDept模型
[Table("CommDept")]
public class CommDept
{
[Key]
public int CommDeptID { get; set; }
public string DeptText { get; set; }
public SelectList DropDownList { get; set; }
}
Index.cshtml.cs
[BindProperty]
public List<CommDept> DropDownList { set; get; }
public void OnGet()
{
var DropDownList = new List<CommDept>();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("SELECT CommDeptID, DeptText FROM CommDept", conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
DropDownList.Add(new CommDept
{
CommDeptID = Convert.ToInt32(rdr.GetString(0)),
DeptText = rdr.GetString(1)
});
}
}
}
var adjList = new CommDept();
adjList.DropDownList = new SelectList(DropDownList, "CommDeptID", "DeptText");
}
Index.cshtml
<select class="form-control rounded" asp-items="Model.DropDownList"></select>
答案 0 :(得分:0)
错误提示,请尝试使用显式类型强制转换:
DropDownList.Add((SelectListItem)new CommDept
{
CommDeptID = Convert.ToInt32(rdr.GetString(0)),
DeptText = rdr.GetString(1)
});
如果这不起作用,则您必须在CommDept类上write a custom Type converter,或者直接使用new SelectListItem { Value = ..., Text = ... }
。