0

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>
abdul hameed
  • 331
  • 4
  • 6

1 Answers1

0

Try this:

Model.attendaceOptionsList.FirstOrDefault(f => f.Value == Model.attendanceList[i]).Selected = true;

@Html.DropdownListFor(model=> model.attendanceList[i],Model.attendaceOptionsList, new { @class = "form-control"})
User3250
  • 2,961
  • 5
  • 29
  • 61
  • That work when I bind only one dropdown for each student. if I bind more dropdowns for each student. like one for attendanceListCourseOne and one for attendanceListCourse2nd. then both dropdown value become same. the later one always select the value of 1st one. – abdul hameed May 22 '17 at 17:05