Home » Asp.Net » Bind DropDownList in Asp.MVC using ViewData object

Bind DropDownList in Asp.MVC using ViewData object

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

Here we will take some fixed Work status list and save it to the ViewData and then in view we will bind ViewData object 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> taskStatus = new List<SelectListItem>();
			taskStatus.Add( new SelectListItem { Text = "New", Value = "0" });
			taskStatus.Add(new SelectListItem { Text = "InProcess", Value = "1" });
			taskStatus.Add(new SelectListItem { Text = "OnHold", Value = "2" });
			taskStatus.Add(new SelectListItem { Text = "Complete", Value = "3" });
			taskStatus.Add(new SelectListItem { Text = "Closed", Value = "4" });
			ViewData["taskStatusList"] = taskStatus;
			return View();
		}
	}
}

Razor View code

@using System.Web.Mvc
@using System.Collections

@{
	ViewBag.Title = "Home Page";
}

@Html.DropDownList("taskStatus",
new SelectList((IEnumerable)ViewData["taskStatusList"], "Value", "Text"))

Above code will produce output as below image.

You can see in the controller we have created a list of SelectListItem object, and then added 1 by 1 value to list. After adding all the required items to list, we have assigned it to the ViewData object, which we have used in the razor view while rednering dropdown control.
In the view we have first cast ViewData to IEnumerable object and then again cast it to SelectList, and then pass field name of select list to display it into the dropdown.
So we have seen 3 different ways to bind a dropdown control in Asp.net MVC

You can download the full working code from here

 

About Coding Sharp

Coding sharp is a blog where you can find the authors personal experience, tutorials, examples, code samples, resources related to C#, Asp.Net, Linq, Ajax, MVC, Entity Framework, SQL Server, jQuery, Visual Studio.

Pages