与DB连接的MvC DropDownList

时间:2017-05-11 12:33:08

标签: c# asp.net-mvc

我有这个下拉列表,用DB中的值填充自己,但是当它到达视图时,它会以某种方式为空。

这是我的模特

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"))`

有人可以告诉我,我做错了什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果您使用ViewData设置列表,则应使用:

@Html.DropDownList("SelectedProblem", 
new SelectList((IEnumerable) ViewData["Problem"], "ID", "Title"))

当您将数据回发到服务器时,将使用第一个参数SelectedProblem