我在下拉列表中选择了值。
查看
@Html.DropDownList("QuestionType", (IEnumerable<SelectListItem>)ViewData["questiontype"], new { id = "QuestionType", @style = "max-width: 200px;width: 200px", @OnChange = "HideForm(this)", @class = "form-control" })
控制器
var questionTypeList = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Automatic", Selected = false },
new SelectListItem { Value = "2", Text = "Custom", Selected = true}
}, "Value", "Text"
).ToList();
var questionType = new SelectList(questionTypeList, "Value", "Text");
ViewData["questiontype"] = questionType;
我希望在视图中选择true = 2但是我的上面的脚本无效,我该如何解决这个问题?
我修改了我的代码。我没有使用绑定到dropdownlist的strongtype。我正在使用viewdata。这是我的代码:
控制器
List<SelectListItem> questionTypeList = new List<SelectListItem>();
questionTypeList.Add(new SelectListItem() { Text = "Automatic", Value = "1" });
questionTypeList.Add(new SelectListItem() { Selected = true, Text = "Custom", Value = "2" });
ViewData["questiontype"] = questionTypeList;
查看
@Html.DropDownList("QuestionType", ViewData["questiontype"] as SelectList, new { id = "QuestionType", @style = "max-width: 200px;width: 200px", @OnChange = "HideForm(this)", @class = "form-control" })
为什么这段代码有用,以及为什么以前的代码不起作用?我很困惑......
答案 0 :(得分:1)
不确定您是否拥有强类型视图,但可以使用
DropdownlistFor(model=>model.QuestionType, selectlistItem)
然后在你的控制器集中
model.QuestionType to 2;
然后
return View(model);