【发布时间】:2016-12-23 15:17:28
【问题描述】:
我想使用 MVC 在下拉列表中从数据库表的列(仅限 1 列)加载数据。
【问题讨论】:
标签: c# asp.net model-view-controller
我想使用 MVC 在下拉列表中从数据库表的列(仅限 1 列)加载数据。
【问题讨论】:
标签: c# asp.net model-view-controller
将列表添加到您的模型中:
public List<string> DropDownList= new List<string>();
然后在你的模型中创建一个函数来从数据库中加载 DropDownList 的数据:
public void GetDropDownList()
{
//Pass your data base connection string here
using (SqlConnection c = new SqlConnection(cString))
//Pass your SQL Query and above created SqlConnection object "c"
using (SqlCommand cmd = new SqlCommand("SELECT Column1 FROM Table", c))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
DropDownList.Add(rdr["Column1"].ToString())
}
}
}
}
最后在 Controller 中,您需要将模型发送到视图:
//Create object of your Model of controller
Model objModel = new Model();
//Call function to load the data for the DropDownList
objModel.GetDropDownList();
//return view with your object of model
return View(objModel);
现在在 Razor 中你可以显示这个:
@Html.DropDownListFor(m => Model.DropDownList);
【讨论】:
请发布您的代码以获得更好的解决方案。否则您可以使用关于 li(html) 元素的数据的 foreach 循环。
【讨论】: