Bind dropdown list using ADO.Net and Entity Framework in Asp.Net MVC

   11/9/2021 6:02:58 PM     Asp.Net MVC Bind Dropdown List using Asp.Net MVC ADO.Net Entity Framework     0

Share us on:

Linkedin GooglePlus

Hi, I am Shubham Kumar, I am going to explain with an example, how to Bind Dropdown List in a different way in ASP.Net MVC Razor. 

Here Dropdown List is populated in all possible ways using ASP.Net MVC.

I am going to bind the dropdown list in a different-different way, I have used ADO.Net and EntityFramwork both for connecting and fetching data from the database.

 

I have used many ways to bind the dropdown list in Asp.Net MVC, there are different- different ways to bind the dropdown list.

1. Bind Dropdown List using ADO.Net     

2. Bind Dropdown List using Entity Framework.

  • Bind Dropdown list with a model using Entity Framework   

  • Bind Dropdown list with view bag Entity Framework

 

now, I am going to populate the dropdown list with database data using ADO.Net in Asp.Net MVC.

Method #1.1:-

I have used Model for binding dropdown list with ADO.Net in Asp.Net MVC 

Database

I have created tblEmp table, which contains the field empId, empName, empCountry.

Table


 CREATE TABLE [dbo].[tblEmp]
   (
       [empId] [int] IDENTITY(1,1) NOT NULL,
       [empName] [varchar](50) NULL,
       [empCountry] [varchar](50) NULL
   )

 

Stored Procedure


  create proc Sp_SelectData
   as
   begin
     select *from tblEmp
   end

 

Controller

In Controller, there are two Action methods.

indexx and BindDdlEmp, I have used indexx method for showing indexx page view. 

I have used BindDdlEmp method for bind dropdown list using a procedure in ASP.Net MVC 

Here, I have used ADO.Net for fetching data from the database and binding it to the model, and then data return to indexx view for the binding dropdown list.

There are all controller codes for the binding dropdown list using Asp.Net MVC.

 


        public ActionResult indexx()
        {
            EmpModel emp = new EmpModel();
            emp.Employees = BindDdlEmp();
            return View(emp);
        }

        public List BindDdlEmp()
        {
            string ConnectionString = ConfigurationManager.ConnectionStrings["CurdConntectionString"].ConnectionString;
            List data = new List();
            SqlConnection Con = new SqlConnection(ConnectionString);
            SqlCommand Com = new SqlCommand();
            Com.Connection = Con;
            Com.CommandText = "Sp_SelectData";
            Com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter _sqlDataAdapter = new SqlDataAdapter(Com);
            DataSet _dtSet = new DataSet();
            _sqlDataAdapter.Fill(_dtSet);

            for (int i = 0; i < _dtSet.Tables[0].Rows.Count; i++)
            {
                data.Add(new SelectListItem
                {
                    Text = _dtSet.Tables[0].Rows[i]["empName"].ToString(),
                    Value = _dtSet.Tables[0].Rows[i]["empId"].ToString()
                });
            }

            return data;
        }
        }       


 

Model

I have created EmpModel model with properties empId, empName,Employees(List<SelectListItem>)

 


    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CurdOperationJqueryMVC.Models
{
    public class EmpModel
    {
        public int empId { get; set; }
        public List Employees { get; set; }
    }
    
    [Table("tblEmp")]
    public class Employee
    {
        [Key]
        public int empId { get; set; }
        public string empName { get; set; }
        public string empCountry { get; set; }
    }
}

 

View

In Indexx View which contains @Html.DropDownListFor() and @Html.DropDownList() both Asp.Net MVC razor control.

Now, I am going to bind the dropdown list using Model in strongly type and non strongly type dropdown list in Asp.Net MVC.

Here, all codes of view which contain @Html.DropDownListFor() and @Html.DropDownList() dropdown list 

 


@model CurdOperationJqueryMVC.Models.EmpModel

@{
    Layout = null;
}
<!DOCTYPE html>
<style>
    .margin {
        margin-top: 2%;
        height: 37px;
        width: 181px;
        margin-left: 67px;
    }
</style>
<html>
<head>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
    <div class="margin">
        @Html.DropDownListFor(m => m.empId,Model.Employees, "----select-----", new { @class = "margin" })

        @Html.DropDownList("Emp",Model.Employees, new { id = "ddlEmployee", @class = "form-control margin" })
    </div>
    }
</body>
</html>

 

Method #1.2:-

Bind Dropdown list with ViewBag using ADO.Net 

Controller

Controller contains two Action methods.

indexx and BindDdlEmp, I have used indexx method for showing indexx page view. 

there are all code for the Bind Dropdown list with ViewBag using ADO.Net.

 


        public ActionResult indexx()
        {
            EmpModel emp = new EmpModel();
            ViewBag.Employees = BindDdlEmp();
            return View(emp);
        }

        public List BindDdlEmp()
        {
            string ConnectionString = ConfigurationManager.ConnectionStrings["CurdConntectionString"].ConnectionString;
            List data = new List();
            SqlConnection Con = new SqlConnection(ConnectionString);
            SqlCommand Com = new SqlCommand();
            Com.Connection = Con;
            Com.CommandText = "Sp_SelectData";
            Com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter _sqlDataAdapter = new SqlDataAdapter(Com);
            DataSet _dtSet = new DataSet();
            _sqlDataAdapter.Fill(_dtSet);

            for (int i = 0; i < _dtSet.Tables[0].Rows.Count; i++)
            {
                data.Add(new SelectListItem
                {
                    Text = _dtSet.Tables[0].Rows[i]["empName"].ToString(),
                    Value = _dtSet.Tables[0].Rows[i]["empId"].ToString()
                });
            }

            return data;
        }
        }       


 

View

here I am going to bind dropdown list @Html.DropDownListFor() and @Html.DropDownList() both Asp.Net MVC razor control.

Now, I am going to bind the dropdown list using ViewBag in strongly type and non-strongaly type dropdown list in Asp.Net MVC.

 


@model CurdOperationJqueryMVC.Models.EmpModel

@{
    Layout = null;
}
<!DOCTYPE html>
<style>
    .margin {
        margin-top: 2%;
        height: 37px;
        width: 181px;
        margin-left: 67px;
    }
</style>
<html>
<head>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
    <div class="margin">
        @Html.DropDownListFor(m => m.empId,  (List<SelectListItem>)(ViewBag.Employees), "----select-----", new { @class = "margin" })

        @Html.DropDownList("Emp", (List<SelectListItem>)(ViewBag.Employees), new { id = "ddlEmployee", @class = "form-control margin" })
    </div>
    }
</body>
</html>

 

Method #2.1:-

2 Bind Dropdown List using Entity Framework.

  2.1. Bind Dropdown list with a model using Entity Framework 

 

Controller

there are two methods that contain all code for the binding dropdown list using model 


using CurdOperationJqueryMVC.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CurdOperationJqueryMVC.Controllers
{
    public class HomeController : Controller
    {
        private DataContext _context;
        public HomeController()
        {
            var type = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
            _context = new DataContext();
        }
        public ActionResult indexx()
        {
            EmpModel obj = new EmpModel();
            obj.Employees = _context.emp.ToList();
            return View(obj);
        }
     }
}
      

 

View

the view contains @Html.DropDownListFor() and @Html.DropDownList() both Asp.Net MVC razor control.

 


@model bindDropDownList.Models.Employee

@{
    Layout = null;
}

<!DOCTYPE html>
<style>
    .margin{
        margin-top:2%;
    }
</style >
<html >
<head >
    <meta name="viewport" content="width=device-width" / >
    <title > Index</title >
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
       <div class="margin">
        @Html.DropDownListFor(m => m.empId,  new SelectList(Model.Employees, "empId", "empName"), "----select-----", new { @class = "margin" })

        @Html.DropDownList("Emp", new SelectList(Model.Employees, "empId", "empName"), new { id = "ddlEmployee", @class = "form-control margin" })
    </div>
    }
</body>
</html>

 

Method #2.2:-

b.Bind Dropdown list with ViewBag using Entity Framework

Controller

there are two methods for binding dropdown lists with ViewBag using Entity Framework in Asp.Net MVC. 

 

View

the view contains @Html.DropDownListFor() and @Html.DropDownList() both Asp.Net MVC razor control.

 


@model bindDropDownList.Models.Employee

@{
    Layout = null;
}

<!DOCTYPE html>
<style>
    .margin{
        margin-top:2%;
    }
</style >
<html >
<head >
    <meta name="viewport" content="width=device-width" / >
    <title > Index</title >
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
       <div class="margin">
        @Html.DropDownListFor(m => m.empId,  new SelectList(ViewBag.Employees, "empId", "empName"), "----select-----", new { @class = "margin" })

        @Html.DropDownList("Emp", new SelectList(ViewBag.Employees, "empId", "empName"), new { id = "ddlEmployee", @class = "form-control margin" })
    </div>
    }
</body>
</html>

Output Screen

Output-Screen

 

 

I hope this article will help you to learn, How to bind dropdown list with Model and ViewBag using Ado.Net and Entity Framework in Asp.Net MVC, if you like this article please share Us on

Shubham Kumar

Shubham Kumar is a founder of AspNetBugs, .NET Team Leader. He has very good experience with designing and developing enterprise-scale applications. He is exprience in ASP.NET MVC,ASP.NET C#, ASP.NET Core, AngularJS, Web API, EPPlus, SQL, Entity Framework, JavaScript, jQuery, Kendo, Windows services etc.