How To Bind DropDownList in ASP.NET MVC

This article describes about how you can bind your mvc DropDownList in different ways.

You can bind DropDownList in many ways. Here I will be describing binding it with static values, with ViewBag dynamic property, with model values and with database objects.


Create a new application with default settings for MVC environment. You will add corresponding ActionResult and Views.

Open HomeController from Controllers folder and add below ActionResult to see different ways of DropDownList bindings.


Binding MVC DropDownList with Static Values

You can have a DropDownList binded with some static values in View itself. Just add a Html helper for DropDownList and provide static list of SelectListItem.

The values added as SelectListItem will be added and displayed in DropDownList.

In this way you do not need to add anything in Controller Action. This method is best suitable when values are pre-defined like Gender, Type etc.

Add below ActionResult in HomeController

    
    public ActionResult StaticBind()
    {
        return View();
    }
        
            

Add new View by right clicking on StaticBind action method and select Add View. This will add a new view under Views -> Home folder.

Add below Html code in StaticBind view.


@Html.DropDownList("Category", new List<SelectListItem>()
{
    new SelectListItem(){ Text= "Beverages", Value = "1"},
    new SelectListItem(){ Text= "Condiments", Value = "2"},
    new SelectListItem(){ Text= "Confections", Value = "3"},
    new SelectListItem(){ Text= "Dairy Products", Value = "4"},
    new SelectListItem(){ Text= "Grains/Cereals", Value = "5"},
    new SelectListItem(){ Text= "Meat/Poultry", Value = "6"},
    new SelectListItem(){ Text= "Produce", Value = "7"},
    new SelectListItem(){ Text= "Seafood", Value = "8"}
}, "Select Category")
    
            

Bind MVC DropDownList with ViewBag property values

With this method you need to provide a List or IEnumerable object of SelectListItem. This object you can assign to ViewBag property and use it in View.

This way is useful when you have dynamic values which needs to be display as values of DropDownList.

Open HomeController from Controllers folder and add below Action method.


public ActionResult BindWithViewBag()
{
    List<SelectListItem> items = new List<SelectListItem>();

    items.Add(new SelectListItem
               {Text="Select Category", Value="0", 
                                    Selected = true });

    items.Add(new SelectListItem
                { Text="Beverages", Value = "1" });

    items.Add(new SelectListItem
                { Text = "Condiments", Value = "2" });

    items.Add(new SelectListItem
                { Text = "Confections", Value = "3" });

    items.Add(new SelectListItem
                { Text = "Dairy Products", Value = "4" });

    items.Add(new SelectListItem
                { Text = "Grains/Cereals", Value = "5" });

    items.Add(new SelectListItem
                { Text = "Meat/Poultry", Value = "6" });

    items.Add(new SelectListItem
                { Text = "Produce", Value = "7" });

    items.Add(new SelectListItem
                { Text = "Seafood", Value = "8" });

    ViewBag.CategoryType = items;

    return View();
}
    
            

We have created a list of SelectListItem and assigned to ViewBag CategoryType property. Now add a view to display those values on screen. Right click on BindWithViewBag action method and select Add View.

Add below Html code in BindWithViewBag view.


@using (Html.BeginForm("CategoryChosen", "Home", 
                FormMethod.Get))
{

    <fieldset>

        Category Type : 

        @Html.DropDownList("CategoryType")
        
    </fieldset>

}
            

The values of CategoryType ViewBag property will be assign to @Html.DropDownList html helper.


Bind MVC DropDownList with Model values

With this method you can bind DropDownList with model values. Model can have any values added in dynamic or static way. For more info on model ASP.NET MVC model example.

This method is useful when you have values coming from Database or dynamic values added in controller.

Add below action method in HomeController


public ActionResult BindWithModel()
{
    List<SelectListItem> items = new List<SelectListItem>();

    items.Add(new SelectListItem 
                { Text = "Select Category", Value = "0", 
                        Selected = true });
    items.Add(new SelectListItem
                { Text = "Beverages", Value = "1" });
    items.Add(new SelectListItem
                { Text = "Condiments", Value = "2" });
    items.Add(new SelectListItem
                { Text = "Confections", Value = "3" });
    items.Add(new SelectListItem
                { Text = "Dairy Products", Value = "4" });
    items.Add(new SelectListItem
                { Text = "Grains/Cereals", Value = "5" });
    items.Add(new SelectListItem
                { Text = "Meat/Poultry", Value = "6" });
    items.Add(new SelectListItem
                { Text = "Produce", Value = "7" });
    items.Add(new SelectListItem
                { Text = "Seafood", Value = "8" });

    var model = new CategoryModel()
    {
        lstCategory = items,
        selected = 1
    };

    return View(model);
}
    
            

Your model is ready with required values. Add View to bind those values with DropDownList.

Add below HTML code to View


@model BindMvcDropdownList.Models.CategoryModel

<h1>Bind MVC DropDownList with Model</h1>

@Html.DropDownListFor(x => x.selected, Model.lstCategory)
    
            

Bind MVC DropDownList with Database values

You can bind your DropDownList with values coming from Database. Like Category names or sub category names stored in database and values can be filter with some values.

In this step create one service class which will read data from database and return required values.

Add one class under Services folder name it as CategoryService. Add below code in CategoryService class which reads Category names from Northwind database.


public static class CategoryService
{
    public static CategoryModel GetAllCategories()
    {
        CategoryModel categories = new CategoryModel();

        string query = string.Format("SELECT [CategoryID], 
                [CategoryName] FROM [Categories]");

        using (SqlConnection con =
                new SqlConnection("your connection string"))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                categories.lstCategory = 
                    new List<SelectListItem>();  

                while (reader.Read())
                {
                    categories.lstCategory.Add(
                        new SelectListItem 
                        { Text = reader.GetString(1), 
                          Value = reader.GetInt32(0).ToString() 
                        });                        
                }
            }
        }

        if(categories.lstCategory.Count > 0 )
            categories.selected = 1; 

        return categories;            
    }        
}
    
            

Your service code is ready, call it from controller and return send those values to View DropDownList. Add below code to HomeController.


public ActionResult BindWithDbValues()
{
    CategoryModel categories = 
                CategoryService.GetAllCategories();
    return View("BindWithModel", categories); 
}
    
            

In return statement we are using already created view. So mentioned "BindWithModel" as name of existing view.


Bind MVC DropDownList with Database and EntityFramework

If you are using entity framework for Database operations you can use below code to bind db values.

    
    var db = new NorthwindDataContext();

    var query = db.Categories.Select(c => new SelectListItem
                {
                    Value = c.CategoryID.ToString(), 
                    Text = c.CategoryName,
                    Selected = c.CategoryID.Equals(3)
                });

    var model = new CategoryModel
                {
                    lstCategory = query.AsEnumerable()
                };
    return View(model);
        
            

You can use existing "BindWithModel" view to display binded list items or you can use below html code.

            
@model CategoryModel

@Html.DropDownListFor(m => m.CategoryId, 
                Model.List, "--Select One--")
                
            

It gives you below output

Bind ASP.NET MVC DropDownList

You can also add values to DropDownList using jQuery.Ajax call. See example on bind cascading MVC DropDownList.

Download source code.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by Bevelyne at 9/2/2017 4:08:00 AM
Thanks for the Knowkedge you've shared to us. For me, i was so excited with this topic, I 've learnt alot from this topic
post comment on dotnetmentors.com