Skip to main content

Bind DropDownList in Asp.MVC using ViewBag object

In our previous article we have seen how to bind fixed value from view and how to bind Range to dropdown list, In this article we will see how to bind ViewBag data to dropdown. Remember we can set any data to ViewBag like from database, from enum, from range, fixed value etc.

Here we will take some fixed country list and save it to the ViewBag and then in view we will bind ViewBag value to the dropdown as shown in below code snippet.

Controller code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MCVApp.Controllers
	public class HomeController : Controller
		public ActionResult Index()
			List<SelectListItem> countryList = new List<SelectListItem>();
			countryList.Add( new SelectListItem { Text = "India", Value = "IN" });
			countryList.Add(new SelectListItem { Text = "United States", Value = "US" });
			countryList.Add(new SelectListItem { Text = "United Kingdom", Value = "UK" });
			countryList.Add(new SelectListItem { Text = "France", Value = "FR" });
			ViewBag.CountryList = countryList;
			return View();

Razor View code

@using System.Web.Mvc

	ViewBag.Title = "Home Page";

ViewBag.CountryList as IEnumerable<SelectListItem>)

Above code will produce output as below image.


In the controller if you see we have created a list of SelectListItem object, and then added 1 by 1 value to the list. After adding all the required items to list, we have assigned it to the ViewBag object, In razor view we have used that ViewBag data for binding a dropdown control.

In this article we have seen how to bind dropdown using ViewBag value, In our next article we will see how to bind a dropdown with ViewData object.