Tuesday, July 8, 2014

MVC Razor - DropdownListFor with index list binding

In MVC Razor, sometimes we feel selected value not reflect when we use indexed selected

Ex:    @Html.DropDownListFor(m => m.EmployeeDetails[0].StateId,
                        Model.StateList,
                        new { @class = "classname" })

in the above example state will not selected as it taken from employeeDetail list.

Change the code as below and it will work

  @Html.DropDownListFor(m => m.EmployeeDetails[0].StateId,
                        new SelectList(Model.StateList, "Value", "Text", Model. EmployeeDetails[0].StateId),
                        new { @class = "classname" })