我想使用MVC在下拉列表中从数据库表的列(仅1列)加载数据。
答案 0 :(得分:2)
将List添加到您的模型中:
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);
现在在剃刀中你可以显示:
@Html.DropDownListFor(m => Model.DropDownList);
答案 1 :(得分:-1)
请发布您的代码以获得更好的解决方案。否则,您可以使用有关li(html)元素的数据的foreach循环。