无法将 ViewBag 信息传递给 DropDownListFor
Can't pass ViewBag info to the DropDownListFor
我有以下问题:
我创建了 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>
怎么办?
问题已解决:在 get 和 post 方法中声明 ViewBags!
使用 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();
}
错误很明显 DropDown 应该是这样的:
ViewBag.DropDown = forDistinct.DistinctBy(x => x.Issue_Type).Select(col=> new SelectListItems { Text= col.Issue_Type,Value=col.Issue_Type.ToString() }).ToList();
因为您的下拉菜单需要 IEnumerable
我有以下问题:
我创建了 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>
怎么办?
问题已解决:在 get 和 post 方法中声明 ViewBags!
使用 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();
}
错误很明显 DropDown 应该是这样的:
ViewBag.DropDown = forDistinct.DistinctBy(x => x.Issue_Type).Select(col=> new SelectListItems { Text= col.Issue_Type,Value=col.Issue_Type.ToString() }).ToList();
因为您的下拉菜单需要 IEnumerable