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.
- DropDownList in ASP.Net MVC
- Cascading Dropdown List With MVC, LINQ to SQL and AJAX
- 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:
- 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.
- We need explicit casting each time we get data from ViewBag.
- We get away from Visual Studio intelligence in cases of ViewBag.
- 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.
- using System.Collections.Generic;
- using System.Web.Mvc;
-
- namespace DropdownExample.Controllers
- {
- public class DataController : Controller
- {
- public ActionResult Index()
- {
- ViewBag.Technologies = new List<SelectListItem>{ new SelectListItem{
- Text="ASP.NET",
- Value = "1"
- },
- new SelectListItem{
- Text="C#",
- Value = "1"
- }};
- return View("Index");
- }
- }
- }
Now we will create a view for the above action with a dropdown list populated by ViewBag as per the following code snippet.
- <div class="row">
- <div class="form-group">
- <label class="col-md-2 control-label">Technology</label>
- <div class="col-md-10">
- @Html.DropDownList("technologies",new SelectList(ViewBag.Technologies,"Value","Text"))
- </div>
- </div>
- </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.
- using System.Collections.Generic;
- using System.Web.Mvc;
-
- namespace DropdownExample.Models
- {
- public class DataViewModel
- {
- public int CountryId { get; set; }
- public List<SelectListItem> Countries
- {
- get
- {
- return new List<SelectListItem>{
- new SelectListItem{
- Text="India",
- Value = "1"
- },
- new SelectListItem{
- Text="USA",
- Value = "2"
- }
- };
- }
- }
- }
- }
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.
- public ActionResult Index()
- {
- DataViewModel model = new DataViewModel();
- return View("Index", model);
- }
After that we update view with model as per the following code snippet.
- @model DropdownExample.Models.DataViewModel
- <div class="row">
- <div class="form-group">
- @Html.LabelFor(m => m.CountryId, new {@class="col-md-2 control-label" })
- <div class="col-md-10">
- @Html.DropDownListFor(m => m.CountryId, Model.Countries, new {@class="form-control" })
- </div>
- </div>
- </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.
- using System.Collections.Generic;
-
- namespace DropdownExample.Models
- {
- public class DataViewModel
- {
- public int CountryId { get; set; }
- public Dictionary<string, int> Countries
- {
- get
- {
- return new Dictionary<string, int>{
- {"India",1},
- {"USA",2},
- {"UK",3}
- };
- }
- }
- }
- }
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.
- @model DropdownExample.Models.DataViewModel
- <div class="row">
- <div class="form-group">
- @Html.LabelFor(m => m.CountryId, new { @class = "col-md-2 control-label" })
- <div class="col-md-10">
- @Html.DropDownListFor(m => m.CountryId, new SelectList(Model.Countries, "Value", "Key"), new { @class = "form-control" })
- </div>
- </div>
- </div>
Read more recent articles on ASP.NET MVC,
- Image Resize In ASP.NET MVC Using Image Resizer
- Partial View In ASP.NET MVC
- Html.Action And Html.RenderAction In ASP.NET MVC
- Set Up Server Environment For ASP.NET MVC Application On Development Machine