MVC - DropDown值不在视图中绑定

时间:2015-08-21 04:13:58

标签: c# asp.net-mvc asp.net-mvc-4 html-helper

在我的视图中,我使用的是Helper DropDown。我面临的问题是not getting binded的数据为DropDown。当我从Controller设置ShiftId的值时,应该在DropDown中选择该值,这在我的情况下不会发生。

@{Dictionary<string, string> shifts = (Dictionary<string, string>)ViewBag.Shifts;}
@Html.DropDownListFor(m => m[i].List[q].ShiftId, new System.Web.Mvc.SelectList(shifts, "Key", "Value"), "Select")

1 个答案:

答案 0 :(得分:2)

你在循环中生成下拉列表,不幸的是这是助手的限制。您需要在每次迭代中生成一个新的SelectList(您正在执行),但您还需要在SelectList构造函数中设置所选的值。

@Html.DropDownListFor(m => m[i].List[q].ShiftId, 
    new SelectList(shifts, "Key", "Value", Model[i].List[q].ShiftId),
    "Select"
)