How To Bind DropDownList in ASP.NET MVC

This article describes 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 the MVC environment. You will add corresponding ActionResult and Views.

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

Binding MVC DropDownList with Static Values

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

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

In this way, you do not need to add anything to 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 the 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 the View.

This way is useful when you have dynamic values that need to be displayed as values of the DropDownList.

Open HomeController from the Controllers folder and add the 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 the screen. Right click on the 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 assigned to @Html.DropDownList the HTML helper.

Bind MVC DropDownList with Model values

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

This method is useful when you have values coming from the Database or dynamic values added in the 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 the 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 the 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 the Services folder name it as CategoryService. Add below code in CategoryService class which reads Category names from the 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 the controller and return send those values to View DropDownList. Add the below code to HomeController.


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

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

Bind MVC DropDownList with Database and EntityFramework

If you are using entity framework for Database operations you can use the 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 the 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.

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


  • geeksarray user
    09/02/2017 04:08 AM Bevelyne

    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

Blog Search





If you like my content please feel free to buy me coffee. Buy Me A Coffee