无法将ViewBag信息传递给DropDownListFor

时间:2015-12-14 12:12:48

标签: asp.net-mvc asp.net-mvc-4 razor html.dropdownlistfor viewbag

我有以下问题:

我创建Db上下文然后将其传输到IQueryable。之后我提取了不同的值。它完美地查询结果(我在调试器中检查过)。我创建了viewbag:

public ActionResult Create()
{
    var forDistinct = db.Cases.AsQueryable();
    var Issue_Type = forDistinct.DistinctBy(x => x.Issue_Type).Select(col => col.Issue_Type).ToList();
    ViewBag.DropDown = new SelectList(Issue_Type);
    return View();
}

我按如下方式设置DropDownListFor:

@Html.DropDownListFor(model => model.Issue_Type, ViewBag.DropDown as IEnumerable<SelectListItem>)

当我尝试保存新项目时,会发生以下错误:

The ViewData item that has the key 'Issue_Type' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>

怎么办?

3 个答案:

答案 0 :(得分:1)

使用这样的Post方法:

[HttpPost]
public ActionResult Create()
{
 var forDistinct = db.Cases.AsQueryable();
 var Issue_Type = forDistinct.DistinctBy(x => x.Issue_Type).Select(col =>
 col.Issue_Type)/*.Select(grp => grp.First()*/.ToList();
 ViewBag.DropDown = new SelectList(Issue_Type);
 return View();
}

答案 1 :(得分:0)

问题解决了:在get和post方法中声明ViewBags!

答案 2 :(得分:0)

错误很明显DropDown应该是:

ViewBag.DropDown = forDistinct.DistinctBy(x => x.Issue_Type).Select(col=> new SelectListItems { Text= col.Issue_Type,Value=col.Issue_Type.ToString() }).ToList();

因为你的下拉期待IEnumerable

相关问题