There are several ways to populate a dropdown control with data. In this article, I have shown you simple ways to populate a dropdown, like directly by hardcoding in the view, using viewdata, viewbag and Ajax.

Procedure

  1. Add MVC3 application project
  2. Add Area “DropdownDemo”
  3. Add a controller to the preceding area “DropdownDemo”

An Index is a default action created when you add a controller. Add a view page for this index action by right-clicking on Index and add View (Index). In this Index action, I have written code for loading the data in a viewdata and a viewbag. ViewData and ViewBag is used to pass data from a controller to a view. In both of them the difference is typecasting. ViewData requires typecasting when used in a view, whereas a Viewbag doesn't require type casting.

Controller Code

  1. commEntities DB = new commEntities();// DB Entity Object
  2. public ActionResult Index()
  3. {
  4. //using viewdata
  5. var dropdownVD = new SelectList(DB.tblStuds.ToList(), "studid", "stud_name");
  6. ViewData["StudDataVD"] = dropdownVD;
  7. //using viewbag
  8. ViewBag.dropdownVD = new SelectList(DB.tblStuds.ToList(), "studid", "stud_name");
  9. return View();
  10. }
  11. public JsonResult GetStudents()//ajax calls this function which will return json object
  12. {
  13. var resultData = DB.tblStuds.Select(c => new { Value = c.studid, Text = c.stud_name }).ToList();
  14. return Json(new { result = resultData },JsonRequestBehavior.AllowGet);
  15. }
View Page code: index.cshtml
  1. @model projStudentInfo.Models.tblStud
  2. @{
  3. ViewBag.Title = "Index";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. <h2>
  7. Different ways of populating dropdown</h2>
  8. <table border="0" cellpadding="0" cellspacing="0">
  9. <thead>
  10. <tr>
  11. <th>
  12. Type
  13. </th>
  14. <th>
  15. Result
  16. </th>
  17. <th>
  18. Code
  19. </th>
  20. <th>
  21. Description
  22. </th>
  23. </tr>
  24. </thead>
  25. <tr>
  26. <td>
  27. In Design Mode
  28. </td>
  29. <td>
  30. @Html.DropDownListFor(c => c.stud_name, new SelectList(
  31. new List<Object>{
  32. new { value = 0 , text = "Red" },
  33. new { value = 1 , text = "Blue" },
  34. new { value = 2 , text = "Green"}
  35. },
  36. "value",
  37. "text", 2))
  38. </td>
  39. <td>
  40. <pre style="color:brown;"> @@Html.DropDownListFor(c => c.stud_name, new SelectList(
  41. new List
  42. <object>{
  43. new { value = 0 , text = "Red" },
  44. new { value = 1 , text = "Blue" },
  45. new { value = 2 , text = "Green"}
  46. },
  47. "value",
  48. "text", 2))</pre>
  49. </td>
  50. <td>
  51. Hardcoded values in design mode only in View, 2 is selected value
  52. </td>
  53. </tr>
  54. <tr>
  55. <td>
  56. Using ViewData
  57. </td>
  58. <td>
  59. @Html.DropDownListFor(c => c.studid, ViewData["StudDataVD"] as SelectList)
  60. </td>
  61. <td>
  62. <pre style="color:brown;"> @@Html.DropDownListFor(c => c.studid, ViewData["StudDataVD"] as SelectList)</pre>
  63. </td>
  64. <td>
  65. ViewData requires type casting
  66. </td>
  67. </tr>
  68. <tr>
  69. <td>
  70. Using ViewBag
  71. </td>
  72. <td>
  73. @Html.DropDownList("dropdownVD") @*String must be same as ViewBag.dropdownVD*@
  74. </td>
  75. <td>
  76. <pre style="color:brown;">@@Html.DropDownList("dropdownVD")</pre>
  77. </td>
  78. <td>
  79. ViewBag doesnt require type casting. DropDownList name must be same as ViewBag name(in
  80. controller)
  81. </td>
  82. </tr>
  83. <tr>
  84. <td>
  85. Using Ajax on page load
  86. </td>
  87. <td>
  88. <select id="ajaxDropdown">
  89. </select>
  90. </td>
  91. <td>
  92. <pre style="color:brown;">$(document).ready(function () {
  93. $.getJSON('@@Url.Action("GetStudents", "DropdownDemo")', function (result) {
  94. PopulateDDList("ajaxDropdown", result.result)
  95. });</pre>
  96. });
  97. </td>
  98. <td>
  99. Json calling GetStudents action which returns json object to jquery result and FillDropdown
  100. is a function for filling dropdown
  101. </td>
  102. </tr>
  103. </table>
  104. <script>
  105. $(document).ready(function () {
  106. $.getJSON('@Url.Action("GetStudents", "DropdownDemo")', function (result) {
  107. FillDropdown("ajaxDropdown", result.result)
  108. });
  109. });
  110. // Generic code for any dropdown to fill called by ajax
  111. function FillDropdown(selector, vData) {
  112. if (vData.length > 0) {
  113. var vItems = [];
  114. for (var i in vData) {
  115. if (vData[i].Selected)
  116. vItems.push('<option selectedselected=selected value="' + vData[i].Value + '">' + vData[i].Text + '</option>');
  117. else
  118. vItems.push('<option value="' + vData[i].Value + '">' + vData[i].Text + '</option>');
  119. }
  120. $('#' + selector).empty();
  121. $('#' + selector).append(vItems.join(''));
  122. return true;
  123. }
  124. else {
  125. $('#' + selector).empty();
  126. return false;
  127. }
  128. }
  129. </script>
  130. <style>
  131. table th {padding:5px; background:#aaa;}
  132. table td { padding:5px; background:#fff; border:1px solid #ddd; }
  133. </style>
In the preceding code FillDropdown is a generic function that is reusable for loading many dropdownlists.



Figure 1: Output

If you know more than the preceding methods then feel free to share in the comments section.

Thanks a lot!