Bind DropDownList Using ViewBag In ASP.NET MVC

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

  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".

  2. "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.

  3. 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:

Now after selecting controller template, click on Add button then the following window appears,


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:
HomeController.cs
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();
        }
    }
}
Step 3: Add 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>

Step 4: Run the application.

After running the application the output will be as in the following screenshot:


From all the above examples, I hope you have learned how to bind dropdownlist using ViewBag in ASP.NET MVC.
Summary
I hope this article is useful for all readers. If you have a suggestion then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode