ASP.NET MVC

Binding Dropdownlist With Database In MVC

In this article, we will learn different ways of binding data in the dropdown list with ASP.NET MVC 5. There are many ways to bind data like Viewbag, ViewData, TempData, jQuery, etc. Here we will learn 5 methods to bind data with the dropdown list.

  • Using ViewBag
  • Using ViewData
  • Using TempData
  • Using Global data
  • Using jQuery

Using ViewBag

Add the following code in Controller.

List<SelectListItem> drpList = new List<SelectListItem>();
drpList.Add(new SelectListItem { Text = "Faisal", Value = "1" });
drpList.Add(new SelectListItem { Text = "Irshad", Value = "1" });
drpList.Add(new SelectListItem { Text = "Kaushik", Value = "1" });
drpList.Add(new SelectListItem { Text = "Jaimin", Value = "1" });
drpList.Add(new SelectListItem { Text = "Kirti", Value = "1" });
ViewBag.DrpListViewBag = drpList;

Now in View add the following code.

<h2>Using Viewbag</h2>
@Html.DropDownList("Names", (IEnumerable<SelectListItem>)ViewBag.DrpListViewBag, "---Please Select---")
<hr />

Using ViewData

Add the following code in Controller.

List<SelectListItem> drpListViewData = new List<SelectListItem>();
drpListViewData.Add(new SelectListItem { Text = "Faisal", Value = "1" });
drpListViewData.Add(new SelectListItem { Text = "Irshad", Value = "1" });
drpListViewData.Add(new SelectListItem { Text = "Kaushik", Value = "1" });
drpListViewData.Add(new SelectListItem { Text = "Jaimin", Value = "1" });
drpListViewData.Add(new SelectListItem { Text = "Kirti", Value = "1" });
ViewData["Names"] = drpListViewData;

Now in View add the following code.

<h2>Using ViewData</h2>
@Html.DropDownList("Names", (IEnumerable<SelectListItem>)ViewData["Names"], "---Please Select---")
<hr />

Using TempData

Add the following code in Controller.

List<SelectListItem> drpListTempData = new List<SelectListItem>();
drpListTempData.Add(new SelectListItem { Text = "Faisal", Value = "1" });
drpListTempData.Add(new SelectListItem { Text = "Irshad", Value = "1" });
drpListTempData.Add(new SelectListItem { Text = "Kaushik", Value = "1" });
drpListTempData.Add(new SelectListItem { Text = "Jaimin", Value = "1" });
drpListTempData.Add(new SelectListItem { Text = "Kirti", Value = "1" });
TempData["Names"] = drpListTempData;

Now in View add the following code.

<h2>Using TempData</h2>
@Html.DropDownList("Names", (IEnumerable<SelectListItem>)TempData["Names"], "---Please Select---")
<hr />

Using Global Data

Add the following code in View.

@{
    //global Data
    List<SelectListItem> drpListGlobal = new List<SelectListItem>();
    drpListGlobal.Add(new SelectListItem { Text = "---Please Select---", Value = "0" });
    drpListGlobal.Add(new SelectListItem { Text = "Faisal", Value = "1" });
    drpListGlobal.Add(new SelectListItem { Text = "Irshad", Value = "1" });
    drpListGlobal.Add(new SelectListItem { Text = "Kaushik", Value = "1" });
    drpListGlobal.Add(new SelectListItem { Text = "Jaimin", Value = "1" });
    drpListGlobal.Add(new SelectListItem { Text = "Kirti", Value = "1" });
}
<h2>Using Global data</h2>
@Html.DropDownList("Names", drpListGlobal)
<hr />

Using jQuery

Here, we will bring data from the database and we are going to use code first approach. If you don’t have knowledge of code first approach then you can refer our article for code approach.

Add the connection string in the Web.Config file present at the root

<connectionStrings>
    <add name="StringDBContext" connectionString="Server=DESKTOP-CGB025P;Initial Catalog=DemoDB;Persist Security Info=False;User ID=sa;Password=******;MultipleActiveResultSets=True;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Now create the Context class in the Models folder.

using System.Data.Entity;

namespace Demo.Models
{
    public class Context : DbContext
    {
        public Context():base("StringDBContext") {}
        public DbSet<Angular> Angulars { get; set; }
    }
}

Now create the table as Angular in the Models folder.

using System.ComponentModel.DataAnnotations;

namespace Demo.Models
{
    public class Angular
    {
        [Key]
        public int Id {get;set;}
        public string Name { get; set; }
        public string Phone { get; set; }
    }
}

Now add the code in the controller for getting data from the database.

public ActionResult GetListData()
        {
            Context _context = new Context();
            var data = _context.Angulars.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

Now in View add the following code.

<h2>Using jQuery</h2>
<select id="drpList"></select>
<script>
    $(document).ready(function () {
        $.ajax({
            url: '/DynamicDropdown/GetListData',
            method: 'GET',
            success: function (res) {
                var html = '';
                $.each(res, function (index, item) {
                    html += '<option>' + item.Name + '</option>'
                });
                $('#drpList').html(html);
            },
            error: function (err) {
                alert(err);
            }
        });
    });
</script>

You can download the source code from here

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago