C# 如何使用数据库中的内容填充@html.dropdownlist?
我目前面临一个问题,希望你能帮助我。我正在努力从数据库中收集信息,以允许下拉列表的数量。下面是我的控制器中的代码C# 如何使用数据库中的内容填充@html.dropdownlist?,c#,sql,asp.net-mvc,C#,Sql,Asp.net Mvc,我目前面临一个问题,希望你能帮助我。我正在努力从数据库中收集信息,以允许下拉列表的数量。下面是我的控制器中的代码 public ActionResult Create() { tblProductColour db = new tblProductColour(); this.ViewData["Id"] = new SelectList(db.tblproducts.ToList(), "Id", "ProductColour"); return View(); } 以下是视图中
public ActionResult Create()
{
tblProductColour db = new tblProductColour();
this.ViewData["Id"] = new SelectList(db.tblproducts.ToList(), "Id", "ProductColour");
return View();
}
以下是视图中使用的代码:
@Html.DropDownList("Id")
提前感谢,
Callum在控制器中,您可以将数据库的内容填充到
视图包中,如下所示:
ViewBag.identifier=new SelectList(db.databaseName,“Id”,“productColor”)代码>
然后在视图中显示ViewBag
,如下所示:
@Html.DropDownList(“标识符”,null,htmlAttributes:new{@class=“form control”})
假设您正在使用引导
。。因此,窗体控件的类
名称
确保dropdownlist是否将用于POST
操作,以将ViewBag
置于控制器的两个操作中
例如
public ActionResult Create()
{
ViewBag.identifier = new SelectList(db.databaseName, "Id", "ProductColour");
}
[HttpPost]
public ActionResult Create([Bind(Include = "Id, ProductColour")] #modelName identify)
{
ViewBag.identifier = new SelectList(db.databaseName, "Id", "ProductColour", identify.Id);
}
假设您将一个连接字符串分配给名为db
的变量,我收到的错误是没有从模型本身传递任何信息。底部的“blockquote”是什么意思?谢谢您的帮助。这已经产生了巨大的变化,让我能够完成这项任务。