我没有为学生出勤创建动态DropDownListFor
型号:
List<Student> studentList {get; set;}
List<String> attendanceList {get; set;}
List<SelectListItems> attendaceOptionsList {get; set;} //Present,absent,leave
控制器:
studentList= context.students.ToList(); //return only 3 students suppose;
attendanceList.Add("Present");
attendanceList.Add("Absent");
attendanceList.Add("Leave");
查看:
<Table>
<tr>
<th>Student name </th>
<th>Attendance status </th>
</tr>
@{ var i = 0; }
@foreach(var student in Model.studentList)
{
<tr> <td>student.Name </td>
<td>@Html.DropdownListFor(model=> model.attendanceList[i],Model.attendaceOptionsList, new { @class = "form-control"})
</td>
</tr>
i++;
}`
</table>
问题:
The dropdowns successfully created but dropdown selected value is not correct.
i.e.
The first dropdown selected value should be Present,
2nd one should Absent and
third dropdown selected value should be Leave.
But I get every dropdown list selected value is Present?
为什么没有选择正确的下拉值? 虽然我已经找到了解决方案,如下所述。但我需要知道为什么这不会选择合适的值。
当前解决方案: 我在页面加载时通过JavaScript更正了下拉列表的选定值
<script>
var attendanceList =@Html.Raw(Json.Encode(Model.attendanceList ));
for (var i = 0; i < attendanceList .length; i++) {
//change the value of dropdown.
$('#attendanceList _' + i + '_').val(attendanceList[i]);
}
</script>
答案 0 :(得分:0)
试试这个:
Model.attendaceOptionsList.FirstOrDefault(f => f.Value == Model.attendanceList[i]).Selected = true;
@Html.DropdownListFor(model=> model.attendanceList[i],Model.attendaceOptionsList, new { @class = "form-control"})