[英]Error displaying database values in dropdown box in c#
我在如何在数据库中显示值的下拉列表时遇到问题。 我的数据库表(类别)包含2列,即类别的ID和标题。 目的是提供一个下拉列表,用户可以在其中选择存储在表中的标题。
模型:
public partial class Category
{
public int Id { get; set; }
public string Title { get; set; }
}
控制器:
public ActionResult Index()
{
private Context db = new Context();
ViewBag.Category = new SelectList(db.Categories, "Id", "Title");
return View();
}
视图:
@model MyApp.Models.Category
<p>
Categories: @Html.DropDownList("Id", "Select a Category")
</p>
我得到的错误是在视图中说:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Id'.
您没有将SelectList
传递给DropDownList()
方法,而是传递了id的属性名称。
@Html.DropDownList("Category", "Select a Category")
要使用重载的DropDownList显式传递SelectList对象,请将ViewBag.Category转换为SelectList。
@Html.DropDownList("CategoryNameOfSelect", (SelectList)ViewBag.Category, "Select a Category")
公共静态MvcHtmlString DropDownList(此HtmlHelper htmlHelper,字符串名称,IEnumerable selectList,字符串optionLabel)
htmlHelper类型:System.Web.Mvc.HtmlHelper此方法扩展的HTML帮助程序实例。
name类型:System.String要返回的表单字段的名称。
selectList类型:System.Collections.Generic.IEnumerable SelectListItem对象的集合,这些对象用于填充下拉列表。
optionLabel类型:System.String默认空项目的文本。 此参数可以为空。
您将viewbag的 category键中的下拉列表项放置在视图中,并在视图中传递了“ Id” ,这是您需要传递Category
的错误
在这里,您将其保存在“类别”键中:
ViewBag.Category = new SelectList(db.Categories, "Id", "Title");
尝试这样:
@Html.DropDownList("Category","Select a Category")
试试这个
@Html.DropDownList("Category", (SelectList)ViewBag.Category, "Select a Category")
要么
@Html.DropDownList("Category", ViewBag.Category as SelectList, "--Select a Category--")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.