Various Ways To Populate Dropdownlist in MVC

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.   
  3.        public ActionResult Index()  
  4.        {  
  5.            //using viewdata  
  6.            var dropdownVD = new SelectList(DB.tblStuds.ToList(), "studid""stud_name");  
  7.            ViewData["StudDataVD"] = dropdownVD;  
  8.            //using viewbag  
  9.            ViewBag.dropdownVD = new SelectList(DB.tblStuds.ToList(), "studid""stud_name");  
  10.            return View();  
  11.        }  
  12.   
  13.        public JsonResult GetStudents()//ajax calls this function which will return json object  
  14.   
  15.        {  
  16.            var resultData = DB.tblStuds.Select(c => new { Value = c.studid, Text = c.stud_name }).ToList();  
  17.            return Json(new { result = resultData },JsonRequestBehavior.AllowGet);  
  18.        }  
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.   
  111.     // Generic code for any dropdown to fill called by ajax  
  112.     function FillDropdown(selector, vData) {  
  113.         if (vData.length > 0) {  
  114.             var vItems = [];  
  115.             for (var i in vData) {  
  116.                 if (vData[i].Selected)  
  117.                     vItems.push('<option selectedselected=selected value="' + vData[i].Value + '">' + vData[i].Text + '</option>');  
  118.                 else  
  119.                     vItems.push('<option value="' + vData[i].Value + '">' + vData[i].Text + '</option>');  
  120.             }  
  121.             $('#' + selector).empty();  
  122.             $('#' + selector).append(vItems.join(''));  
  123.             return true;  
  124.         }  
  125.         else {  
  126.             $('#' + selector).empty();  
  127.             return false;  
  128.         }  
  129.     }  
  130. </script>  
  131. <style>  
  132.     table th {padding:5px; background:#aaa;}  
  133.     table td { padding:5px; background:#fff; border:1px solid #ddd; }  
  134. </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! 

Up Next
    Ebook Download
    View all
    Learn
    View all