[英]MvC DropDownList with connection to DB
我有一個下拉菜單,使用數據庫中的值填充自身,但是在進入視圖時,不知何故為null。
這是我的模特
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;
}
}
這是我的控制器
public ActionResult Index()
{
GetProblems();
return View("~/Views/OurFolder.cshtml");
}
public ActionResult GetProblems()
{
ListProblem list = new ListProblem();
List<ListProblem> l = new List<ListProblem>();
l = list.GetProblems();
ViewData["Problem"] = l;
return View("~/Views/OurFolder.cshtml", list);
}
在我看來
@Html.DropDownListFor(model=>model.Id,new `SelectList(Model.Title,"ID","Title","Select option"))`
有人可以告訴我,我做錯了什么以及如何解決這個問題?
如果使用ViewData
設置列表,則應使用:
@Html.DropDownList("SelectedProblem",
new SelectList((IEnumerable) ViewData["Problem"], "ID", "Title"))
當您將數據回發到服務器時,將使用第一個參數SelectedProblem
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.