什么应该是Enumerable <selectlistitem> </selectlistitem>的数据类型

时间:2012-08-23 09:02:47

标签: asp.net-mvc-3 razor model-binding

我正在使用mvc 3 razor,问题是使用剃须刀助手记录数据库中的dropdownlist值:

 @Html.DropDownListFor(m => m.Question,   (IEnumerable<SelectListItem>)ViewBag.QuestionList)

在这里,我的观点是使用模型绑定。而在数据库中,问题列是sting数据类型(varchar),在运行应用程序时,它在提交表单后显示以下错误

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

我应该在这里更改以避免错误,我必须使用模型绑定。

1 个答案:

答案 0 :(得分:0)

  

我应该在这里更改以避免错误,我必须使用模型绑定。

您应该确保在呈现此视图的控制器操作中,您已使用ViewBag.QuestionList填充了IEnumerable<SelectListItem>属性。在重新显示包含此DropDown的相同视图时,人们通常会忘记在POST操作中执行此操作:

IEnumerable<SelectListItem> items = ... 
ViewBag.QuestionList = items;
return View(someModel);

还要确保模型上的Question属性是标量类型(字符串,整数,...)而不是复杂类型。如果它是复杂类型,则需要选择相应的标量属性以将所选值绑定到:

@Html.DropDownListFor(
    m => m.Question.QuestionId, 
    (IEnumerable<SelectListItem>)ViewBag.QuestionList
)