Binding Data to DropDown in MVC
- @using (Html.BeginForm())
- {
- <table>
- <tr>
- <td>
- @Html.DropDownList("Shifts", ViewBag.ShiftData as SelectList, "--Select shifts--", new { })</td>
- </tr>
- </table>
- }
-
- <table>
- <tr>
- <td><select id="Shifts" name="Shifts"><option value="">--Select shifts--</option>
- <option value="1">Shift-A</option>
- <option value="2">Shift-B</option>
- <option value="3">Shift-C</option>
- <option value="4">Shift-D</option>
- <option value="5">Shift-E</option>
- </select></td>
- </tr>
- </table>
- - The first option is taken for name and id.
-
- <td>@Html.DropDownListFor(m=>m.ShiftId,ViewBag.ShiftData as SelectList,"--Select shifts--",new{})</td>
- <td>
- <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>
- <option value="1">Shift-A</option>
- <option value="2">Shift-B</option>
- <option value="3">Shift-C</option>
- <option value="4">Shift-D</option>
- <option value="5">Shift-E</option>
- </select>
- </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
Showshift3.cshtml
- getShifts() is the Extra method added to ER_Shift Class.
DataBase
DatabaseValues