Dropdown List In ASP.NET MVC - Part Two

In this article you will learn about the dropdown list In ASP.NET MVC.

Introduction

This article discusses why we should avoid ViewBag to populate dropdown lists and how to populate dropdown lists on a view. We need to show a dropdown list which contains data on view. As we pass data from controller to view we have the option to store static data in ViewBag or model property. The following articles are also related to populating a dropdown list in MVC application.

  1. DropDownList in ASP.Net MVC
  2. Cascading Dropdown List With MVC, LINQ to SQL and AJAX
  3. Creating a DropDownList For Enums in ASP.Net MVC

Is ViewBag BAD ?

Most of the developers use ViewBag to populate dropdown lists from static data. As per my opinion, it’s not good practice to populate dropdown lists by ViewBag data. The ViewBag is a dynamic property that takes advantage of new dynamic features in C# 4.0. It's also used to pass data from a controller to a view. In short, The ViewBag property is simply a wrapper around the ViewData that exposes the ViewData dictionary as a dynamic object.

As ViewBag is just dictionaries of dynamically typed objects, we have some limitations with it as follows:

  1. It's checking runtime, that’s why when we misspell ViewBag then we get NULL value of it on view. As it doesn’t check compile time that’s why misspelling ViewBag can create potential problems in the application.
  2. We need explicit casting each time we get data from ViewBag.
  3. We get away from Visual Studio intelligence in cases of ViewBag.
  4. We don’t have some IDE support options such as Navigate to all Uses and Go to Definition.

By default we have a ViewBag.Title field created and our templates also get it, so it’s okay.

We have created an example which populates a dropdown list by ViewBag. First of all we created a controller which has an action method. We assigned values to ViewBag in the action method as per the following code snippet.

  1. using System.Collections.Generic;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace DropdownExample.Controllers  
  5. {  
  6.     public class DataController : Controller  
  7.     {  
  8.         public ActionResult Index()  
  9.         {  
  10.             ViewBag.Technologies = new List<SelectListItem>{ new SelectListItem{  
  11.                 Text="ASP.NET",  
  12.                 Value = "1"  
  13.             },  
  14.             new SelectListItem{  
  15.                 Text="C#",  
  16.                 Value = "1"  
  17.             }};  
  18.             return View("Index");  
  19.         }  
  20.     }  
  21. }  
Now we will create a view for the above action with a dropdown list populated by ViewBag as per the following code snippet.
  1. <div class="row">  
  2.     <div class="form-group">  
  3.         <label class="col-md-2 control-label">Technology</label>         
  4.         <div class="col-md-10">  
  5.             @Html.DropDownList("technologies",new SelectList(ViewBag.Technologies,"Value","Text"))              
  6.         </div>  
  7.     </div>  
  8. </div>  
Don’t be LAZY !

I would prefer view modal to populate dropdown list from static data. Whenever you want to pass data from controller to view, you must use view modal as per MVC (Modal-View-Controller) convention. The view modal avoids potential errors at compile time. We create a controller and a view in which show dropdown list.

We use the same controller and action method as per the above example but we created a view model as per the following code snippet.
  1. using System.Collections.Generic;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace DropdownExample.Models  
  5. {  
  6.     public class DataViewModel  
  7.     {  
  8.         public int CountryId { getset; }  
  9.         public List<SelectListItem> Countries  
  10.         {  
  11.             get  
  12.             {  
  13.                 return new List<SelectListItem>{  
  14.                 new SelectListItem{  
  15.                     Text="India",  
  16.                     Value = "1"  
  17.                 },  
  18.                   new SelectListItem{  
  19.                     Text="USA",  
  20.                     Value = "2"  
  21.                 }  
  22.             };  
  23.             }  
  24.         }  
  25.     }  
  26. }  
Now we make changes in the action method of controller to bind strongly typed view to UI. The following code snippet is for the same.
  1. public ActionResult Index()  
  2.         {  
  3.             DataViewModel model = new DataViewModel();  
  4.             return View("Index", model);  
  5.         }   
After that we update view with model as per the following code snippet.
  1. @model DropdownExample.Models.DataViewModel  
  2. <div class="row">  
  3.     <div class="form-group">  
  4.         @Html.LabelFor(m => m.CountryId, new {@class="col-md-2 control-label" })        
  5.         <div class="col-md-10">  
  6.             @Html.DropDownListFor(m => m.CountryId, Model.Countries, new {@class="form-control" })  
  7.         </div>  
  8.     </div>  
  9. </div>  
Populate Dropdown List Using Dictionary

Let's see another example in which we bind a dictionary to dropdown list and populate it accordingly. We created a dictionary type property in model which has static data rather than dynamic data from the database to keep this example simple. The following code snippet is for the model DataViewModel.
  1. using System.Collections.Generic;  
  2.   
  3. namespace DropdownExample.Models  
  4. {  
  5.     public class DataViewModel  
  6.     {  
  7.         public int CountryId { getset; }  
  8.         public Dictionary<stringint> Countries  
  9.         {  
  10.             get  
  11.             {  
  12.                 return new Dictionary<stringint>{  
  13.                 {"India",1},  
  14.                 {"USA",2},  
  15.                 {"UK",3}  
  16.             };  
  17.             }  
  18.         }  
  19.     }  
  20. }  
We have unchanged the action method of controller but made small changes on view to bind dictionary to dropdown list as per the following code snippet.
  1. @model DropdownExample.Models.DataViewModel  
  2. <div class="row">  
  3.     <div class="form-group">  
  4.         @Html.LabelFor(m => m.CountryId, new { @class = "col-md-2 control-label" })  
  5.         <div class="col-md-10">  
  6.             @Html.DropDownListFor(m => m.CountryId, new SelectList(Model.Countries, "Value", "Key"), new { @class = "form-control" })  
  7.         </div>  
  8.     </div>  
  9. </div>  
Read more recent articles on ASP.NET MVC, 
  1. Image Resize In ASP.NET MVC Using Image Resizer
  2. Partial View In ASP.NET MVC
  3. Html.Action And Html.RenderAction In ASP.NET MVC
  4. Set Up Server Environment For ASP.NET MVC Application On Development Machine