我想使用MVC从下拉列表的数据库表的列(仅1列)中加载数据。
将列表添加到模型中:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句