In this tutorial will talk about how to bind dropdownlist in mvc using viewbag from database, this is very easy process.
Step to Bind Dropdown list from Database.
1.Create a country table
2.Insert Country Data in country table
3.Create a procedure and execute.
4.Make Connection in Web Config.
5.Call the procedure from controller.
6.Get the data into Datatable and convert it into list for
7.Store in ViewBag.
Let's See the Above Step in Detail
Create a table in MS SQL Server
Create Databse dotnet
Use dotnet
Create table tbl_country
(
countryid int identity primary key,
countryname varchar(100)
)
Insert Data into tbl_country table
insert into tbl_country(countryname)values('India')
insert into tbl_country(countryname)values('UK')
insert into tbl_country(countryname)values('US')
Create a Procedure
create proc dbo.BindCountryDropDown
as
begin
Select countryid,countryname from tbl_country
end
Make Connection in web Config
<connectionStrings>
<add name="MYCON" connectionString="Data Source=MSI;Initial Catalog=dotnet;integrated security=true;" />
</connectionStrings>
Call the procedure in HomeController
public class HomeController : Controller
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MYCON"].ConnectionString);
public ActionResult BindDropDown()
{
DataTable dt = new DataTable();
//Fill Data from Databse here
con.Open();
SqlCommand cmd = new SqlCommand("BindCountryDropDown", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
ViewBag.CountryList = BindDropDown(dt);
return View();
}
public static List<SelectListItem> BindDropDown(DataTable dt)
{
List<SelectListItem> lst = new List<SelectListItem>();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow item in dt.Rows)
{
lst.Add(new SelectListItem()
{
Text = Convert.ToString(item[1]),
Value = Convert.ToString(item[0])
});
}
}
else
{
lst.Add(new SelectListItem() { Text = "--none--", Value = "" });
}
return lst;
}
}
Bind ViewBag on CsHTML page from controller
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>BindDropDown</title>
</head>
<body>
<div>
@Html.DropDownList("ddlRetailer", (List<SelectListItem>)ViewBag.CountryList, "Select Country", new { @id = "ddlCountry" })
</div>
</body>
</html>
Post a Comment