C# 连接到数据库的MvC下拉列表
我有一个下拉列表,它用DB中的值填充自己,但是当它到达视图时,不知何故是空的 这是我的模型C# 连接到数据库的MvC下拉列表,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个下拉列表,它用DB中的值填充自己,但是当它到达视图时,不知何故是空的 这是我的模型 public class ListProblem { SqlConnection conn = new SqlConnection(); List<ListProblem> ProblemList = new List<ListProblem>(); public string Title { get; set; }
public class ListProblem
{
SqlConnection conn = new SqlConnection();
List<ListProblem> ProblemList = new List<ListProblem>();
public string Title { get; set; }
public int ID { get; set; }
ListProblem p = null;
public List<ListProblem> GetProblems()
{
conn.ConnectionString = "Data Source=IBWS05\\MSSQLSERVER2012;Initial Catalog=Houston;Integrated Security=True";
conn.Open();
using (conn)
{
SqlCommand cmd = new SqlCommand("Select Title from Problems");
cmd.Connection = conn;
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
p = new ListProblem();
p.Title = rd["Title"].ToString();
ProblemList.Add(p);
}
}
return ProblemList;
}
}
有人能告诉我,我做错了什么以及如何解决这个问题吗?如果您使用
ViewData
设置列表,那么您应该使用:
@Html.DropDownList("SelectedProblem",
new SelectList((IEnumerable) ViewData["Problem"], "ID", "Title"))
第一个参数
SelectedProblem
在您将数据发回服务器时使用。您为视图提供了一个ListProblem
的列表,但它在视图中看起来不像是您的模型类型(但您尚未显示)。而且,FWIW,这不是一个模型,你不应该让你的模型做所有的逻辑。
@Html.DropDownListFor(model=>model.Id,new `SelectList(Model.Title,"ID","Title","Select option"))`
@Html.DropDownList("SelectedProblem",
new SelectList((IEnumerable) ViewData["Problem"], "ID", "Title"))