MVC dropdown binding best ways

Bind dropdownlistfor with empty string? Bind dropdown with enum? Bind drop down from database? bind dropdown on change?

To Bind a DropDownListFor or DropDown in asp.net MVC from database, from enum or from hard coded values, most people suggest to add a property in the model with IEnumarable or IList. We can use it but not very helpful because after every postback we will need to fill the list again otherwise it will be null. So using ViewBag is not a bad idea, we will use it in our article.

What we will see in this discussion:

  1. Bind DropDown with hard coded values
  2. Bind DropDown with records from database
  3. Bind DropDown with Enum
  4. Bind DropDown on change of other DropDown's value

1. Bind DropDown with hard coded values

We will try to write both controller code and view in every case, so let's see our first example by using hard coded value

    public ActionResult Index()
    {       
        ViewBag.Active = new List<SelectListItem> {                  
                 new SelectListItem { Text = "Yes", Value = "1"},                   
                 new SelectListItem { Text = "No", Value = "0"}
             };
        var model = new ProductModel();
        return View(model);
    }

In the view, I am not going to show all the label and other model detail. Here IsActie is the model value which will come from database for existing records otherwise null or default value fromthe model, I used the class name from bootstrap.

@Html.DropDownListFor(model => model.IsActive,
   new SelectList(ViewBag.Active, "Value", "Text"), 
   "Select status",
    new { @class = "form-control" })

If it is hard coded values and is a big list then we can create a separate method to create the list otherwise directly we can declare it in view rather than passing from controller view as we did in our above example, see how

@Html.DropDownListFor(model => model.Category,
    new SelectList(new List<SelectListItem> {                  
             new SelectListItem { Text = "Yes", Value = "1"},                   
             new SelectListItem { Text = "No", Value = "0"}
         }, "Value", "Text"), 
    "Select status",
     new { @class = "form-control" })

It doesn't looks good but good thing is that we don't need to create the list again and again on postback, which we will see latter.


2. Bind DropDown with records from database

If you will explore a little bit, you will found most of the people suggest to convert the record into SelectList in controller or in model before passing to view. Is that really required or is a good practice? I cannot say about others but for me, it is really frustrating to convert my table into SelectList every time. If not then is there any way to directly bind the dropdown from a table records, yes, we will see it in this example:

I have a table category which we will use in this example, here is the table structure:

public partial class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public bool IsActive { get; set; }
}

Controller code:

// GET: Products
public ActionResult Create()
{
    var db = new MyDBEntities();
    ViewBag.Categories = db.Categories.Where(x => x.IsActive);
    var model = new ProductModel();
    return View(model);
}   

// POST: Create Product
public ActionResult Create(ProductModel model)
{
    var db = new MyDBEntities();
    if (ModelState.IsValid)
    {
        // code to save record  and redirect to listing page
    }
    // If model is not valid then reload categories from database
    ViewBag.Categories = db.Categories.Where(x => x.IsActive);
    return View(model);
}

In our GET action we are fetching all active categories from database and passing to view by using ViewBag. In POST action we try to validate the posted data by using ModelState.IsValid method, if valid, save data and redirect user to your desired page otherwise, re-populate the the categories before returning the user to page to fix the issue. Now we will see our view html

@Html.DropDownListFor(model => model.Category,
    new SelectList(ViewBag.Categories, "CategoryID", "CategoryName"), 
    "Select Category",
    new { @class = "form-control" })

As you noticed, we directly pass the table records to view after fetching from database without converting to Select List and converted into Select List directly into the view, which is easy and save time. If we will do the same in controller then we need to convert the list in both GET as well as POST action.


3. Bind DropDown with Enum

There are two ways to bind and save the records, and it's all depends on requirement, whether we want to save the number or text value of the enum, we will try both. Let's first create an enum say Language, I am adding those language which I read write and speak

public enum Language
{
    Arabic,
    English,
    Hindi,
    Spanish,
    Urdu
}

If we need to save the text or say bind with text then

// In controller
ViewBag.Languages = Enum.GetValues(typeof(Language)).Cast<Language>();

// In View
@Html.DropDownListFor(model => model.Language,
        new SelectList(ViewBag.Languages),
        "Select language",
        new { @class = "form-control" })

As in most cases we want to use value and text, so we need to create a structure or class and create the list of it from enum which we will use in this example:

We will create a structure which we can use for entire application

public struct DDL
{
    public int Value { get; set; }
    public String Text { get; set; }
}

Now create the list of DLL by using Language enum foreach, and assign to ViewBag.Languages

var languages = new List<DDL>();
foreach (Language lang in Enum.GetValues(typeof(Language)))
    languages.Add(new DDL { Value = (int)lang, Text= lang.ToString() });

ViewBag.Languages = languages;

In view, binding is same as earlier:

@Html.DropDownListFor(model => model.Language,
      new SelectList(ViewBag.Languages, "Value", "Text"),
      "Select status",
      new { @class = "form-control" })

Now when we will post the page, it will post the language Id not the text.


4. Bind DropDown on change of other DropDown's value

It is already become a big article so adding this feature will go on the bottom and will easily ignored. So decided to write it in another article soon and will add link here.

MVC DropDownListFor fill on selection change of another dropdown

Let me know if you have any question, I'll be more than happy to help.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • dropdown
  • dropdownlist
  • dropdownlistfor
  • mvc
  • enum
By Ali Adravi On 04 Apr, 15  Viewed: 30,755

Other blogs you may like

Angularjs dropdown select value, text, multiple values with demo

Angularjs dropdown/slect have more option than any other .net language dropdownlist, we can bind and get only Id or Text or both from dropdown, even we can bind and get more than two values like value, text and role from a dropdown and even more. We can try to see all the possible ways to bind the... By Ali Adravi   On 05 Sep 2015  Viewed: 16,900

Angularjs Cascading Dropdown/Select with demo

Cascading dropdown with angularjs is easier than MVC and ASP.Net. In Angularjs ng-change is the best event to hook the function to get the second dropdown list items. In this article, we will try to fill the state dropdown on selection change of country and then fill the city dropdown on change... By Ali Adravi   On 06 Aug 2015  Viewed: 33,854

MVC EnumDropdownListFor bind with enum example

In MVC we have EnumDropDownListFor which we can directly bind with our any enum, it is very similar to DropDownListFor. In this article we will try to create an enum and use it into our model and see how we can bind and save it into the database. As we know we cannot keep space in the name of emum... By Ali Adravi   On 15 May 2015  Viewed: 10,152

MVC DropDownListFor fill on selection change of another dropdown

Binding DropDownListFor from enum, database and some hard coded values in our previous article [MVC dropdown binding best ways][1]. In this article we will try to bind child Dropdown on selection change of parent Dropdown, say Country to State or Sate to City, by using jQuery which will call an... By Ali Adravi   On 11 Apr 2015  Viewed: 107,465

ActionResult VS ViewResult in MVC

In MVC controls there are different type of action result we use as a return type from a controller action method in which ViewResult, ActionResult and JsonResult are commonly used. In this article we will learn what are the available action results and which one we need to use in which... By Ali Adravi   On 19 Jul 2013  Viewed: 2,971