×

iFour Logo

Different ways of Binding Razor DropDownList in ASP.NET MVC 5

Kapil Panchal July 28, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause

Summarize this article with:

Different ways of Binding Razor DropDownList in ASP.NET MVC 5

DropDownList


A dropdown menu is a method to show a huge list of options since only one choice is displayed initially until someone activates the dropdown box.

DropDownList1

 

Figure 1: DropDownList

 

What is Razor View in MVC?


Razor View is a markup syntax that lets us embed server-based code into web apps using C#. It is not a programming language, just a server-side markup language.

Razor has no specific relations to ASP.NET MVC because it is a general-purpose template engine. We can use it anywhere for HTML like output generation. It is just used in MVC to produce an HTML-like view from web apps.

Razor

Figure 2: Razo

We can have a template file that is a mixture of some literal text with some code snippets. We combine that template with some data or specific model where the data is meant to appear and then we execute the template to generate our output.

It is similar to ASPX files. ASPX files otherwise called templates have literal text with a bit of C# code and these together help to display specific frame or content to the user.


  <% foreach=""> 
           <%: html.actionlink=""> |
           <%: html.actionlink="">|
           <%: html.actionlink="">
         
           <%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: html.actionlink="">
         
           <%: string.format=""><%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: html.actionlink="">
         <%: string.format=""><%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: html.actionlink="">
  <%}%>
  
  @foreach (var item in Model) { 
           @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
           @Html.ActionLink("Details", "Details", new { id = item.ID }) |
           @Html.ActionLink("Delete", "Delete", new { id = item.ID }) 
           @item.Name 
           @String.Format("{0,g}", item.JoiningDate) 
  } 
  

How Do I Bind an ASP.NET MVC DropDownList in MVC Razor?


To populate the DropDownList in MVC using Razor, we can use multiple ways like ViewBag, ViewData, Tempdata, jQuery, Model, Database, AJAX, and Hardcoding in View.

DropdownList using Hardcoded data in view

Populating With Hardcoded Data
@Html.DropDownList("MySkills", new List<% foreach=""><%: string.format=""><%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: htmlactionlink=""><%}%>
{
   new SelectListItem{ Text="ASP.NET MVC", Value = "1" },
   new SelectListItem{ Text="ASP.NET WEB API", Value = "2" },
   new SelectListItem{ Text="ENTITY FRAMEWORK", Value = "3" },
   new SelectListItem{ Text="DOCUSIGN", Value = "4" },
   new SelectListItem{ Text="ORCHARD CMS", Value = "5" },
   new SelectListItem{ Text="JQUERY", Value = "6" },
   new SelectListItem{ Text="ZENDESK", Value = "7" },
   new SelectListItem{ Text="LINQ", Value = "8" },
   new SelectListItem{ Text="C#", Value = "9" },
   new SelectListItem{ Text="GOOGLE ANALYTICS", Value = "10" },
})
  
  

DropdownList using Viewbag

public ActionResult Index() {
  #region ViewBag
  List < SelectListItem > mySkills = new List < SelectListItem > () {
      new SelectListItem {
          Text = "ASP.NET MVC", Value = "1"
      },
      new SelectListItem {
          Text = "ASP.NET WEB API", Value = "2"
      },
      new SelectListItem {
          Text = "ENTITY FRAMEWORK", Value = "3"
      },
      new SelectListItem {
          Text = "DOCUSIGN", Value = "4"
      },
      new SelectListItem {
          Text = "ORCHARD CMS", Value = "5"
      },
      new SelectListItem {
          Text = "JQUERY", Value = "6"
      },
      new SelectListItem {
          Text = "ZENDESK", Value = "7"
      },
      new SelectListItem {
          Text = "LINQ", Value = "8"
      },
      new SelectListItem {
          Text = "C#", Value = "9"
      },
      new SelectListItem {
          Text = "GOOGLE ANALYTICS", Value = "10"
      },
  };
  ViewBag.MySkills = mySkills;
  #endregion
  return View();
}



  Populating With ViewBag Data 
  @Html.DropDownList("MySkills", (IEnumerable
            <% foreach=""><%: string.format=""><%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: html.actionlink=""><%}%>)ViewBag.MySkills) 


DropdownListusing ViewData

public ActionResult Index() {
  #region ViewData
  List < SelectListItem > mySkills = new List < SelectListItem > () {
      new SelectListItem {
          Text = "ASP.NET MVC", Value = "1"
      },
      new SelectListItem {
          Text = "ASP.NET WEB API", Value = "2"
      },
      new SelectListItem {
          Text = "ENTITY FRAMEWORK", Value = "3"
      },
      new SelectListItem {
          Text = "DOCUSIGN", Value = "4"
      },
      new SelectListItem {
          Text = "ORCHARD CMS", Value = "5"
      },
      new SelectListItem {
          Text = "JQUERY", Value = "6"
      },
      new SelectListItem {
          Text = "ZENDESK", Value = "7"
      },
      new SelectListItem {
          Text = "LINQ", Value = "8"
      },
      new SelectListItem {
          Text = "C#", Value = "9"
      },
      new SelectListItem {
          Text = "GOOGLE ANALYTICS", Value = "10"
      },
  };
  ViewData["MySkills"] = mySkills;
  #endregion
}


  Populating With ViewData Data 
  @Html.DropDownList("MySkills", (IEnumerable
            <% foreach=""><%: string.format=""><%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: html.actionlink=""><%}%>)ViewData["MySkills"]) 


DropdownList using TempData

#region TempData
List < SelectListItem > mySkills = new List < SelectListItem > () {
    new SelectListItem {
        Text = "ASP.NET MVC", Value = "1"
    },
    new SelectListItem {
        Text = "ASP.NET WEB API", Value = "2"
    },
    new SelectListItem {
        Text = "ENTITY FRAMEWORK", Value = "3"
    },
    new SelectListItem {
        Text = "DOCUSIGN", Value = "4"
    },
    new SelectListItem {
        Text = "ORCHARD CMS", Value = "5"
    },
    new SelectListItem {
        Text = "JQUERY", Value = "6"
    },
    new SelectListItem {
        Text = "ZENDESK", Value = "7"
    },
    new SelectListItem {
        Text = "LINQ", Value = "8"
    },
    new SelectListItem {
        Text = "C#", Value = "9"
    },
    new SelectListItem {
        Text = "GOOGLE ANALYTICS", Value = "10"
    },
};
 TempData["MySkills"] = mySkills;
 #endregion
  
  
  Populating With TempData Data 
  @Html.DropDownList("MySkills", (IEnumerable
            <% foreach=""><%: string.format=""><%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: html.actionlink=""><%}%>)TempData["MySkills"]) 
  
  

DropdownList using Enum

  public enum MySkills {
    ASPNETMVC,
    ASPNETWEPAPI,
    CSHARP,
    DOCUSIGN,
    JQUERY
}

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

var myskill = new List < ConvertEnum > ();
foreach(MySkills lang in Enum.GetValues(typeof(MySkills)))
myskill.Add(new ConvertEnum {
    Value = (int) lang, Text = lang.ToString()
});
ViewBag.MySkillEnum = myskill;


     Populating From Enum 
     @Html.DropDownList("MySkills", new SelectList(ViewBag.MySkillEnum, "Value", "Text")) 

DropdownList using Database with Entity Framework

  using(CSharpCornerEntities cshparpEntity = new CSharpCornerEntities()) {
    var fromDatabaseEF = new SelectList(cshparpEntity.MySkills.ToList(), "ID", "Name");
    ViewData["DBMySkills"] = fromDatabaseEF;
}


     Populating With Database and EF 
     @Html.DropDownList("MySkills", (IEnumerable
            <% foreach=""><%: string.format=""><%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: html.actionlink=""><%}%>)ViewData["DBMySkills"]) 


DropdownList using Jquery Ajax with JSON Data

  public JsonResult ReturnJSONDataToAJax() //It will be fired from Jquery ajax call
{
    CSharpCornerEntities cshparpEntity = new CSharpCornerEntities();
    var jsonData = cshparpEntity.MySkills.ToList();
    return Json(jsonData, JsonRequestBehavior.AllowGet);
}





     Populating With Json Data 
     @Html.DropDownList("FromJson", new SelectList(Enumerable.Empty
            <% foreach=""><%: string.format=""><%: item.name=""><%: html.actionlink=""><%: html.actionlink=""><%: html.actionlink=""><%}%>())) 


DropdownList using Model

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace VariousWayBindingDropDownListInMVC5.Models {
    public class MySkills {
        public int ID {
            get;
            set;
        }
        public string Name {
            get;
            set;
        }
        public IEnumerable < SelectListItem > Skills {
            get;
            set;
        }
    }
}

var model = new VariousWayBindingDropDownListInMVC5.Models.MySkills();
using(CSharpCornerEntities cshparpEntity = new CSharpCornerEntities()) {
    var dbData = cshparpEntity.MySkills.ToList();
    model.Skills = GetSelectListItems(dbData);
}

private IEnumerable < SelectListItem > GetSelectListItems(IEnumerable < MySkill > elements) {
    var selectList = new List < SelectListItem > ();
    foreach(var element in elements) {
        selectList.Add(new SelectListItem {
            Value = element.ID.ToString(),
                Text = element.Name
        });
    }
    return selectList;
}

@model VariousWayBindingDropDownListInMVC5.Models.MySkills

     Populating With Model Data 
     @Html.DropDownList("FromModel", Model.Skills) 

DropdownList using Global Static Data in View

  @ {
    List < SelectListItem > listItems = new List < SelectListItem > ();
    listItems.Add(new SelectListItem {
        Text = "ASP.NET MVC",
            Value = "1"
    });
    listItems.Add(new SelectListItem {
        Text = "ASP.NET WEB API",
            Value = "2",
            Selected = true
    });
    listItems.Add(new SelectListItem {
        Text = "DOCUSIGN",
            Value = "3"
    });
    listItems.Add(new SelectListItem {
        Text = "C#",
            Value = "4"
    });
} < tr > < td > Populating With Global static Data < /td> < td > @Html.DropDownList("StaticData", listItems) < /td> < /tr>
output200

Figure 3: Output

Conclusion


In this article, we discussed DropDownList and Razor View basics. We also discussed different ways to implement the DropDownList using Razor. Many of them get stuck with binding dropdown elements using MVC. As it is an important concept, this blog will help them resolve their concerns of dropdown list binding.

FAQs

1. How do I bind an ASP.NET MVC DropDownList in Razor?

You can bind an ASP.NET MVC DropDownList using a ViewModel, ViewBag, ViewData, or data from a database. A ViewModel is the best choice for most projects.

2. How do I load data into an ASP.NET MVC DropDownList from a database?

You can get the data using Entity Framework, create a SelectList, and pass it to the Razor view to show dynamic dropdown options.

3. Which is the best ASP.NET MVC dropdown menu in the market?

There is no single best ASP.NET MVC dropdown menu in the market. The built-in DropDownList works well for most projects, while tools like Select2 or Kendo UI are useful for advanced features.

4. Why is my ASP.NET MVC DropDownList not showing the selected value?

This mostly happens when the selected value is not passed correctly, or the dropdown data is not loaded again after form validation.

5. Which method should I use to bind an ASP.NET MVC DropDownList?

For small projects, ViewBag or ViewData can work well. For larger applications, using a ViewModel with Entity Framework is the better and more reliable option.

Different ways of Binding Razor DropDownList in ASP.NET MVC 5 DropDownList A dropdown menu is a method to show a huge list of options since only one choice is displayed initially until someone activates the dropdown box.   Figure 1: DropDownList   What is Razor View in MVC? Razor View is a markup syntax that lets us embed server-based code into web apps using C#. It is not a programming language, just a server-side markup language. Razor has no specific relations to ASP.NET MVC because it is a general-purpose template engine. We can use it anywhere for HTML like output generation. It is just used in MVC to produce an HTML-like view from web apps. Figure 2: Razo We can have a template file that is a mixture of some literal text with some code snippets. We combine that template with some data or specific model where the data is meant to appear and then we execute the template to generate our output. It is similar to ASPX files. ASPX files otherwise called templates have literal text with a bit of C# code and these together help to display specific frame or content to the user.   | |       @foreach (var item in Model) {  @Html.ActionLink("Edit", "Edit", new { id = item.ID }) | @Html.ActionLink("Details", "Details", new { id = item.ID }) | @Html.ActionLink("Delete", "Delete", new { id = item.ID })  @item.Name  @String.Format("{0,g}", item.JoiningDate)  } Read More: Razor Pages Vs Mvc In Asp.net How Do I Bind an ASP.NET MVC DropDownList in MVC Razor? To populate the DropDownList in MVC using Razor, we can use multiple ways like ViewBag, ViewData, Tempdata, jQuery, Model, Database, AJAX, and Hardcoding in View. DropdownList using Hardcoded data in view Populating With Hardcoded Data @Html.DropDownList("MySkills", new List { new SelectListItem{ Text="ASP.NET MVC", Value = "1" }, new SelectListItem{ Text="ASP.NET WEB API", Value = "2" }, new SelectListItem{ Text="ENTITY FRAMEWORK", Value = "3" }, new SelectListItem{ Text="DOCUSIGN", Value = "4" }, new SelectListItem{ Text="ORCHARD CMS", Value = "5" }, new SelectListItem{ Text="JQUERY", Value = "6" }, new SelectListItem{ Text="ZENDESK", Value = "7" }, new SelectListItem{ Text="LINQ", Value = "8" }, new SelectListItem{ Text="C#", Value = "9" }, new SelectListItem{ Text="GOOGLE ANALYTICS", Value = "10" }, }) DropdownList using Viewbag public ActionResult Index() { #region ViewBag List mySkills = new List () { new SelectListItem { Text = "ASP.NET MVC", Value = "1" }, new SelectListItem { Text = "ASP.NET WEB API", Value = "2" }, new SelectListItem { Text = "ENTITY FRAMEWORK", Value = "3" }, new SelectListItem { Text = "DOCUSIGN", Value = "4" }, new SelectListItem { Text = "ORCHARD CMS", Value = "5" }, new SelectListItem { Text = "JQUERY", Value = "6" }, new SelectListItem { Text = "ZENDESK", Value = "7" }, new SelectListItem { Text = "LINQ", Value = "8" }, new SelectListItem { Text = "C#", Value = "9" }, new SelectListItem { Text = "GOOGLE ANALYTICS", Value = "10" }, }; ViewBag.MySkills = mySkills; #endregion return View(); } Populating With ViewBag Data @Html.DropDownList("MySkills", (IEnumerable )ViewBag.MySkills) DropdownListusing ViewData public ActionResult Index() { #region ViewData List mySkills = new List () { new SelectListItem { Text = "ASP.NET MVC", Value = "1" }, new SelectListItem { Text = "ASP.NET WEB API", Value = "2" }, new SelectListItem { Text = "ENTITY FRAMEWORK", Value = "3" }, new SelectListItem { Text = "DOCUSIGN", Value = "4" }, new SelectListItem { Text = "ORCHARD CMS", Value = "5" }, new SelectListItem { Text = "JQUERY", Value = "6" }, new SelectListItem { Text = "ZENDESK", Value = "7" }, new SelectListItem { Text = "LINQ", Value = "8" }, new SelectListItem { Text = "C#", Value = "9" }, new SelectListItem { Text = "GOOGLE ANALYTICS", Value = "10" }, }; ViewData["MySkills"] = mySkills; #endregion } Populating With ViewData Data @Html.DropDownList("MySkills", (IEnumerable )ViewData["MySkills"]) DropdownList using TempData #region TempData List mySkills = new List () { new SelectListItem { Text = "ASP.NET MVC", Value = "1" }, new SelectListItem { Text = "ASP.NET WEB API", Value = "2" }, new SelectListItem { Text = "ENTITY FRAMEWORK", Value = "3" }, new SelectListItem { Text = "DOCUSIGN", Value = "4" }, new SelectListItem { Text = "ORCHARD CMS", Value = "5" }, new SelectListItem { Text = "JQUERY", Value = "6" }, new SelectListItem { Text = "ZENDESK", Value = "7" }, new SelectListItem { Text = "LINQ", Value = "8" }, new SelectListItem { Text = "C#", Value = "9" }, new SelectListItem { Text = "GOOGLE ANALYTICS", Value = "10" }, }; TempData["MySkills"] = mySkills; #endregion Populating With TempData Data @Html.DropDownList("MySkills", (IEnumerable )TempData["MySkills"]) Searching for Reliable .Net Development Company LET'S DISCUSS DropdownList using Enum public enum MySkills { ASPNETMVC, ASPNETWEPAPI, CSHARP, DOCUSIGN, JQUERY } public struct ConvertEnum { public int Value { get; set; } public String Text { get; set; } } var myskill = new List (); foreach(MySkills lang in Enum.GetValues(typeof(MySkills))) myskill.Add(new ConvertEnum { Value = (int) lang, Text = lang.ToString() }); ViewBag.MySkillEnum = myskill; Populating From Enum @Html.DropDownList("MySkills", new SelectList(ViewBag.MySkillEnum, "Value", "Text")) DropdownList using Database with Entity Framework using(CSharpCornerEntities cshparpEntity = new CSharpCornerEntities()) { var fromDatabaseEF = new SelectList(cshparpEntity.MySkills.ToList(), "ID", "Name"); ViewData["DBMySkills"] = fromDatabaseEF; } Populating With Database and EF @Html.DropDownList("MySkills", (IEnumerable )ViewData["DBMySkills"]) DropdownList using Jquery Ajax with JSON Data public JsonResult ReturnJSONDataToAJax() //It will be fired from Jquery ajax call { CSharpCornerEntities cshparpEntity = new CSharpCornerEntities(); var jsonData = cshparpEntity.MySkills.ToList(); return Json(jsonData, JsonRequestBehavior.AllowGet); } Populating With Json Data @Html.DropDownList("FromJson", new SelectList(Enumerable.Empty ())) DropdownList using Model using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace VariousWayBindingDropDownListInMVC5.Models { public class MySkills { public int ID { get; set; } public string Name { get; set; } public IEnumerable Skills { get; set; } } } var model = new VariousWayBindingDropDownListInMVC5.Models.MySkills(); using(CSharpCornerEntities cshparpEntity = new CSharpCornerEntities()) { var dbData = cshparpEntity.MySkills.ToList(); model.Skills = GetSelectListItems(dbData); } private IEnumerable GetSelectListItems(IEnumerable elements) { var selectList = new List (); foreach(var element in elements) { selectList.Add(new SelectListItem { Value = element.ID.ToString(), Text = element.Name }); } return selectList; } @model VariousWayBindingDropDownListInMVC5.Models.MySkills Populating With Model Data @Html.DropDownList("FromModel", Model.Skills) DropdownList using Global Static Data in View @ { List listItems = new List (); listItems.Add(new SelectListItem { Text = "ASP.NET MVC", Value = "1" }); listItems.Add(new SelectListItem { Text = "ASP.NET WEB API", Value = "2", Selected = true }); listItems.Add(new SelectListItem { Text = "DOCUSIGN", Value = "3" }); listItems.Add(new SelectListItem { Text = "C#", Value = "4" }); } Populating With Global static Data @Html.DropDownList("StaticData", listItems) Figure 3: Output Conclusion In this article, we discussed DropDownList and Razor View basics. We also discussed different ways to implement the DropDownList using Razor. Many of them get stuck with binding dropdown elements using MVC. As it is an important concept, this blog will help them resolve their concerns of dropdown list binding. FAQs 1. How do I bind an ASP.NET MVC DropDownList in Razor? You can bind an ASP.NET MVC DropDownList using a ViewModel, ViewBag, ViewData, or data from a database. A ViewModel is the best choice for most projects. 2. How do I load data into an ASP.NET MVC DropDownList from a database? You can get the data using Entity Framework, create a SelectList, and pass it to the Razor view to show dynamic dropdown options. 3. Which is the best ASP.NET MVC dropdown menu in the market? There is no single best ASP.NET MVC dropdown menu in the market. The built-in DropDownList works well for most projects, while tools like Select2 or Kendo UI are useful for advanced features. 4. Why is my ASP.NET MVC DropDownList not showing the selected value? This mostly happens when the selected value is not passed correctly, or the dropdown data is not loaded again after form validation. 5. Which method should I use to bind an ASP.NET MVC DropDownList? For small projects, ViewBag or ViewData can work well. For larger applications, using a ViewModel with Entity Framework is the better and more reliable option.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about Azure Cloud, Data Analytics, AI, & Workflow Automation and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
What’s New in ASP.NET Core 10 – Key Features & Expert Insights

16 September 2025

Kapil Panchal

What’s New in ASP.NET Core 10 – Key Features & Expert Insights

We tracked the evolution of .NET 9 on Reddit, and watched the heated debates on .NET 6 vs .NET 8. And just when we thought that things had finally settled, Microsoft drops another...

What’s New in .NET 9?

27 September 2024

Kapil Panchal

What’s New in .NET 9?

Today, we’re thrilled to present you with the first glimpse of .NET 9 release and let you know what features and updates you can anticipate in this new version. Various professionals believe that it’s the right time to explore and adopt the latest version of .NET for your upcoming projects. It is even recommended for projects built using .NET 6 or .NET 8, due to the framework updates made in this version.

UWP vs WPF - Key Differences Explained!

24 September 2024

Kapil Panchal

UWP vs WPF - Key Differences Explained!

Several experts, particularly those just starting out, often find themselves confused about WPF and UWP, wondering if they are the same. Since they are used to create great UIs for...