【问题标题】:There is no ViewData item of type 'IEnumerable<SelectListItem>' @Html.DropDownList没有 'IEnumerable<SelectListItem>' @Html.DropDownList 类型的 ViewData 项
【发布时间】:2019-05-16 05:47:26
【问题描述】:

这里出现问题:

@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>

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

写你的@Html.DropDownList()如下:

@Html.DropDownList("KategoriId", ViewBag.KategoriId as SelectList,"Select Ketegory Id", htmlAttributes: new { @class = "form-control" })

这应该可以解决您的问题!

【讨论】:

    【解决方案2】:

    您可以在 CSHTML 中将 ViewBag 类型转换为 IEnumerable&lt;SelectListItem&gt;

    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`
    

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2016-05-11
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多