【发布时间】:2020-01-13 18:14:31
【问题描述】:
我正在尝试使用以下代码绑定数据库中的下拉列表值,但它在视图中抛出错误。我做了多个练习,但无法达到输出。有人可以帮我解决这个问题吗?
错误:
没有具有键“LocID”的“IEnumerable”类型的 ViewData 项。
操作代码:
public ActionResult Add()
{
List<Location> listObj = new List<Location>();
{
listObj = LocDrpDwnList();
};
List<SelectListItem> LocList = new List<SelectListItem>();
foreach(var item in listObj)
{
LocList.Add(new SelectListItem
{
Text = item.LocationName.ToString(),
Value = Convert.ToInt32(item.LocID).ToString()
}) ;
}
ViewBag.LocID = LocList;
return View();
}
从数据库中获取列表值的方法:
public List<Location> LocDrpDwnList()
{
SqlConnection db = new SqlConnection(conn);
string query = "SELECT * FROM Location";
SqlCommand cmd = new SqlCommand(query, db);
db.Open();
List<Location> loclist = new List<Location>();
using (IDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
Location obj = new Location();
if (dataReader["LocID"] != DBNull.Value)
{
if (dataReader["LocID"] != DBNull.Value) { obj.LocID = Convert.ToInt32(dataReader["LocID"]); }
if (dataReader["LocationName"] != DBNull.Value) { obj.LocationName = (string)dataReader["LocationName"]; }
loclist.Add(obj);
}
}
return loclist;
}
}
下拉控件的视图:
@Html.DropDownListFor(model => model.LocID, (IEnumerable<SelectListItem>)ViewBag.LocID , "Select Location", new { htmlAttributes = new { @class = "form-control" } })
【问题讨论】:
-
你如何返回model.locID?它是否正在行动中?另外,您的视图使用什么模型?你能告诉我们(相关部分)查看页面吗?
标签: c# asp.net-mvc list drop-down-menu