I have created no of dynamic DropDownListFor for student attendance as
Model:
List<Student> studentList {get; set;}
List<String> attendanceList {get; set;}
List<SelectListItems> attendaceOptionsList {get; set;} //Present,absent,leave
Controller:
studentList= context.students.ToList(); //return only 3 students suppose;
attendanceList.Add("Present");
attendanceList.Add("Absent");
attendanceList.Add("Leave");
View:
<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>
Problem:
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?
Why it does not select the correct value for drop down? Although i have find the solution for this as mention below. but i need to know why this does not select the proper value.
Current Solution: I have corrected the dropdown's selected value through JavaScript on page load as
<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>