问题在这里发生:
@Html.DropDownList("KategoriId", null, htmlAttributes: new { @class = "form-control" })
这是我的控制器:
public ActionResult Create()
{
ViewBag.KategoriId = new SelectList(db.Kategoris, "KategoriId", "KategoriAdi");
return View();
}
这是我的观点:
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.KategoriId, "KategoriId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("KategoriId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.KategoriId, "", new { @class = "text-danger" })
</div>
</div>
答案 0 :(得分:0)
编写您的@Html.DropDownList()
如下:
@Html.DropDownList("KategoriId", ViewBag.KategoriId as SelectList,"Select Ketegory Id", htmlAttributes: new { @class = "form-control" })
这应该可以解决您的问题!
答案 1 :(得分:0)
您可以在CSHTML中将ViewBag类型转换为IEnumerable<SelectListItem>
:
CSHTML代码:
@Html.DropDownList("your_key", (IEnumerable<SelectListItem>)ViewBag.KategoriId, "--Select Any--", new { @class = "form-control"})
控制器代码:
IList<SelectListItem> items = new List<SelectListItem>();
foreach (var item in db.Kategoris.ToList())
{
SelectListItem sellist = new SelectListItem();
sellist.Value = item.code.ToString();
sellist.Text = item.name;
items.Add(sellist);
}
ViewBag.KategoriId = items; // at the end this item should be list of `SelectListItem`