Binding Data to DropDown in MVC
  1. @using (Html.BeginForm())
  2. {
  3. <table>
  4. <tr>
  5. <td>
  6. @Html.DropDownList("Shifts", ViewBag.ShiftData as SelectList, "--Select shifts--", new { })</td>
  7. </tr>
  8. </table>
  9. }
  10. <table>
  11. <tr>
  12. <td><select id="Shifts" name="Shifts"><option value="">--Select shifts--</option>
  13. <option value="1">Shift-A</option>
  14. <option value="2">Shift-B</option>
  15. <option value="3">Shift-C</option>
  16. <option value="4">Shift-D</option>
  17. <option value="5">Shift-E</option>
  18. </select></td>
  19. </tr>
  20. </table>
  21. - The first option is taken for name and id.
  22. <td>@Html.DropDownListFor(m=>m.ShiftId,ViewBag.ShiftData as SelectList,"--Select shifts--",new{})</td>
  23. <td>
  24. <select data-val="true" data-val-number="The field ShiftId must be a number." data-val-required="The ShiftId field is required." id="ShiftId" name="ShiftId"><option value="">--Select shifts--</option>
  25. <option value="1">Shift-A</option>
  26. <option value="2">Shift-B</option>
  27. <option value="3">Shift-C</option>
  28. <option value="4">Shift-D</option>
  29. <option value="5">Shift-E</option>
  30. </select>
  31. </td>

- The first argument “ m=>m.ShiftId” is for name and id of Select attribute.

- The data – (attribute tags) are generated automatically because ShiftId in the model is of integer type.

- If we change the first argument to Description then these data –(attribute tags will disappear)

HomeController

showShifts1.cshtml

showShifts2.cshtml

Showshift3.cshtml

DropDownList.Helpers:

ERShift.cs

- getShifts() is the Extra method added to ER_Shift Class.

DataBase

DatabaseValues