没有ViewData项类型'IEnumerable <selectlistitem>'具有密钥xxxxxx </selectlistitem>

时间:2014-03-06 16:55:36

标签: c# asp.net asp.net-mvc

我在ASP.NET MVC 5中创建了一个下拉列表,在提交后我收到了上述错误。

控制器代码:

public ActionResult Create()
{
    List<SelectListItem> items = new List<SelectListItem>();
    items.Add(new SelectListItem { Text = "No", Value = "0" });
    items.Add(new SelectListItem { Text = "Yes", Value = "1" });
    items.Add(new SelectListItem { Text =  "Unconfirmed", Value = "null" });
    ViewBag.DropDown = items;
    return View();
}

查看代码:

@Html.DropDownListFor(model => model.VisitRequested, (IEnumerable<SelectListItem>)ViewBag.Dropdown, new { onClick = "showHide();" })

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

替换下面的

@Html.DropDownListFor(model => model.VisitRequested, 
    (IEnumerable<SelectListItem>)ViewBag.Dropdown, 
    new { onClick = "showHide();" })

使用

@Html.DropDownListFor(model => model.VisitRequested, 
    new SelectList(ViewBag.Dropdown, "Value", "Text"), 
    new { onClick = "showHide();" })

这将解决您的问题!!

答案 1 :(得分:0)

我尝试了这个,它对我有用

public ActionResult Create()
        {
            var items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "No", Value = "0" });
            items.Add(new SelectListItem { Text = "Yes", Value = "1" });
            items.Add(new SelectListItem { Text = "Unconfirmed", Value = "null" });
            ViewBag.DropDown = items;
            return View();
        }

用这个

@Html.DropDownListFor(model => model.VisitRequested, 
    new SelectList(ViewBag.Dropdown, "Value", "Text"), 
    new { onClick = "showHide();" })