Many times we need to bind the DropDownList using ViewBag in ASP.NET MVC. So by considering above requirement I have
decided to write this article . Let us learn it step by step through
creating a simple MVC application.
Step 1: Create an ASP.NET MVC Application
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
- Choose MVC empty application option and click on OK
Step 2: Add controller class.
Right click on Controller folder in the created MVC application, give the class name Home or as you wish as in the following:
Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class as in the following:
using System.Collections.Generic; using System.Web.Mvc; namespace BindDropDownlistUsingViewBag.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { //Creating generic list List<SelectListItem> ObjList = new List<SelectListItem>() { new SelectListItem { Text = "Latur", Value = "1" }, new SelectListItem { Text = "Pune", Value = "2" }, new SelectListItem { Text = "Mumbai", Value = "3" }, new SelectListItem { Text = "Delhi", Value = "4" }, }; //Assigning generic list to ViewBag ViewBag.Locations = ObjList; return View(); } } }
Add empty view named Index.cshtml and write the following code
@{ ViewBag.Title = "www.compilemode.com"; } <div class="form-horizontal"> <div class="col-md-12" style="margin-top:20px"> @Html.DropDownList("ObjList", (IEnumerable<SelectListItem>)ViewBag.Locations, new { id = "ddlLocations", @class = "form-control" }) </div> </div>
Post a Comment