Binding Data To DropDownList in MVC 4

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.   
  11. <table>  
  12.  <tr>  
  13. <td><select id="Shifts" name="Shifts"><option value="">--Select shifts--</option>  
  14. <option value="1">Shift-A</option>  
  15. <option value="2">Shift-B</option>  
  16. <option value="3">Shift-C</option>  
  17. <option value="4">Shift-D</option>  
  18. <option value="5">Shift-E</option>  
  19. </select></td>  
  20.         </tr>  
  21.     </table>  
  22. -   The first option is taken for name and id.  
  23.   
  24. <td>@Html.DropDownListFor(m=>m.ShiftId,ViewBag.ShiftData as SelectList,"--Select shifts--",new{})</td>  
  25. <td>  
  26. <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>  
  27. <option value="1">Shift-A</option>  
  28. <option value="2">Shift-B</option>  
  29. <option value="3">Shift-C</option>  
  30. <option value="4">Shift-D</option>  
  31. <option value="5">Shift-E</option>  
  32. </select>  
  33. </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
 
 
Next Recommended Reading How To Bind DropDownList In ASP.NET MVC