Binding DropDownList in Asp.Net MVC

by Sachin Singh


Posted on Monday, 22 March 2021

Tags: Binding DropDownList in Asp.Net MVC DroDownList in MVC How to bind DropDownList in MVC Bind DropDownListFor in MVC DropDownListFor in MVC

A registration form or any type of form that takes user input is impossible to exist without a dropdownList, yes, the DropDownList may contain static values like, selecting a security question out of ten given options or selecting favorite place out of ten given places, etc. But, most often we need to bind the DropDownList from server-side data, the data that we fetch from the database, for example, displaying a list of countries or cities in a DropDownList.

In Asp.Net MVC, we use Html helpers to design the user interface, Html helpers are nothing but extension methods on HtmlHelper class, which could be accessed in Razor view using "@Html" syntax.

Asp.Net MVC provides the following two flavors of DropDownList in the form of Html helper.
    1. DropDownList()
    2. DropDownListFor()

The first one is simple whereas the second one is strongly typed, which means it will be bind with a model. It is very easy to bind a DropDownList with server-side data, but beginners always find it difficult because there are so many overloaded versions of DropDownList() helper or DropDownListFor() helper, are available, which always creates confusion.

Better is to forget all the overloaded versions and stick with the version which takes 4 parameters as shown below.

DropDownList
DropDownList Html helper
DropDownListFor
DropDownListFor Html helper

As you can see in the figures shown above, both the DropDownList helper and DropDownListFor helper takes 4 parameters. Among all the 4 parameters, the 2nd parameter is the most important, this parameter only is responsible for populating the DropDownList's options with text and value.

Common steps for binding DropDownList or DropDownListFor

Step 1. Create the necessary Model class.

Suppose, we have to bind the countries to the dropdown, then our first step should be to create a Model class named Country as shown below.


   public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Step 2. create a method for retrieving data from database and expose List of Object.


 public List<Country> GetCountries()
 {
   // here you can fetch data from database, for conveninet i am using static values.
  //var db = new myDbContext();
   //var countryList = db.Countries.ToList();

   List<Country> countryList = new List<Country>() 
   { 
    new Country(){Id=1,Name="India"},
    new Country(){Id=2,Name="Japan"},
    new Country(){Id=3,Name="Pakistan"},
   };
   return countryList;
  }

Step 3. Create a ViewModel having following two properties.
  1. First property will carry the selected value on Post request.
  2. second property will be used for populating the DropDownList or DropDownListFor with data.


  public class ddlCountryVM
  {
   public int selectedCountryId { get; set; }
   public IEnumerable<SelectListItem> CountryList { get; set; }
  }

Step 4. Create an Action Method which exposes a view and populate the 2nd property of viewmodel.


 public ActionResult Index()
 {
  ddlCountryVM ddlcountries = new ddlCountryVM();
  ddlcountries.CountryList = GetCountries().Select(x => new SelectListItem()
  { 
     Text=x.Name,
     Value=x.Id.ToString()
   });
   return View(ddlcountries);
 }

Step 5. Design the Form (Bootstrap preferred)


@model jquery.Models.ddlCountryVM 
@{
    Layout = null;
 }

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> 
</head>
<body>
    <div> 
        <form action="/" method="post">
            <h2>DropDownList example</h2>
            <div class="form-group">
                <label for="Name">Select list:</label>
                @Html.DropDownList("ddlCountry", (IEnumerable<SelectListItem>)Model.CountryList, "--Please select--", new { @class = "form-control" })
            </div>
            <br />
            <h2>DropDownListFor example</h2>
            <div class="form-group">
                <label for="selectedCountryId">Select list:</label>
                @Html.DropDownListFor(x => x.selectedCountryId, (IEnumerable<SelectListItem>)Model.CountryList, "--Please select--", new { @class = "form-control" })
            </div>
            <input type="submit" name="btnSubmit" value="Submit" />
        </form>
    </div>
</body>
</html>

Now, Run the application and you will find both the dropdowns has been binded correctly.

DropDownList Result
DropDownList output
DropDownListFor
DropDownListFor output