.Net Core Razor Page DropDownList with ADO.Net



我正在使用带有 ADO.Net 的.Net Core Razor Pages。我正在尝试从数据库中提取数据并插入到下拉列表中。我得到这个

无法将类型"System.Collections.Generic.List"隐式转换为"System.Collections.Generic.IEnumerable"。存在显式转换(您是否缺少强制转换?

通信部模型

[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>

正如错误所暗示的那样,请尝试使用显式类型转换:

DropDownList.Add((SelectListItem)new CommDept
{
CommDeptID = Convert.ToInt32(rdr.GetString(0)),
DeptText = rdr.GetString(1)
});

如果这不起作用,那么要么你必须在你的类 CommDept 上编写一个自定义的类型转换器,要么直接使用new SelectListItem { Value = ..., Text = ... }

最新更新