Share us on:
Hi, i am Shubham Kumar, I am going to explain with example, how to bind dropdown list using procedure in ASP.Net MVC.
Here dropdown list will be populated from database in ASP.Net MVC.
Dropdown binding is very improtant for any project, now I am going to explain, how to bind dropdown list from database in ASP.Net MVC.
I have used ADO.Net for connecting backend to frontend, its used to we can get data from database in c# method.
Database
I have created tblEmp table, which contains field empId, empName, empCountry.
CREATE TABLE [dbo].[tblEmp]
(
[empId] [int] IDENTITY(1,1) NOT NULL,
[empName] [varchar](50) NULL,
[empCountry] [varchar](50) NULL
)
Controller
In Controller there are two Action methods.
Index and BindEmp, i have used Index method for showing index page view.
i have used BindEmp method for bind dropdown list using procedure in ASP.Net MVC
public ActionResult Index()
{
Employee emp = new Employee();
emp.Employees = BindEmp();
return View(emp);
}
public List BindEmp()
{
string strConnectionString = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
List items = new List();
SqlConnection _sqlCon = new SqlConnection(strConnectionString);
SqlCommand _sqlCom = new SqlCommand();
_sqlCom.Connection = _sqlCon;
_sqlCom.CommandText = "Sp_SelectData";
_sqlCom.CommandType = CommandType.StoredProcedure;
SqlDataAdapter _sqlDataAdapter = new SqlDataAdapter(_sqlCom);
DataSet _dtSet = new DataSet();
_sqlDataAdapter.Fill(_dtSet);
for (int i = 0; i < _dtSet.Tables[0].Rows.Count; i++)
{
items.Add(new SelectListItem
{
Text = _dtSet.Tables[0].Rows[i]["empName"].ToString(),
Value = _dtSet.Tables[0].Rows[i]["empId"].ToString()
});
}
return items;
}
Model
I have created Employee model with properties empId, empName,Employees(List<SelectListItem>)
[Table("tblEmp")]
public class Employee
{
[Key]
public int empId { get; set; }
public string empName { get; set; }
public string empCountry { get; set; }
}
View
In View there is a Dropdown List it bind with Employee Model. i have bind this dropdown list from database using ADO.Net,
When page load, that time HomeController called,where action result Index, which return data from database using ADO.Net For a binding dropdown list
@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, Model.Employees, "----select-----")
</div>
}
</body>
</html>
Output Screen
I hope this article will help you to learn, How to bind dropdown list from database in ASP.Net MVC, if you like this article please share Us on