ASP.NET MVC dropdown-list from database

后端 未结 6 1462
梦如初夏
梦如初夏 2020-12-05 05:30

Ok, so I\'m new to this whole MVC-world, but it seems to be a pretty good way of getting things done and I\'m trying to make it work here.

The problem is: I can\'t g

6条回答
  •  盖世英雄少女心
    2020-12-05 05:55

    Add the SelectList to your model:

    public SelectList DropDownList { get; set; }
    

    build the class for that collection:

    public class MyListTable
    {
        public string Key { get; set; }
        public string Display { get; set; }
    }
    

    and then in your controller, load the data for the MyListTable class from the database:

    var list = new List();
    
    using (SqlConnection c = new SqlConnection(cString))
    using (SqlCommand cmd = new SqlCommand("SELECT KeyField, DisplayField FROM Table", c))
    {
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                list.Add(new MyListTable
                {
                    Key = rdr.GetString(0),
                    Display = rdr.GetString(1)
                });
            }
        }
    }
    
    var model = new users();
    model.DropDownList = new SelectList(list, "Key", "Display");
    

    and then finally, you need to send your model to the view:

    return View(model);
    

    Now in the Razor you can display this:

    @Html.DropDownListFor(m => Model.DropDownList);
    

    You of course can name these things better names, but you get the idea.

提交回复
热议问题