Before starting the topic I assume that you are familiar with jQuery and MVC. If you are not familiar with this I strongly recommended you that first learn jQuery and MVC basics, then start reading this article.
As we all know, to add a value with a HTML dropdown list statically is very easy. It is done directly using a “select” tag , but when we have a requirement to add the data in HTML dropdownlist dynamically then the things change. At that time we must load the data from the database.
Let me tell you step-by-step how to load the data dynamically from a database to a HTML dropdown list with a simple example.
Step 1
In the very first step you need to create a table in your database.
For my example I have created a table called IBank.
Let's create this table with the following command in SQL Server:
- Create table IBank (iBid int, sBName varchar(50));
- Insert into IBank(iBid, sBName)
- values
- (001, 'SBI'),
- (002, 'ICCI'),
- (003, 'HDFC')
In the second step we need to create a view with one Dropdown control.
To do this I added an ActionResult in my controller named DynamicDropdown.
- public ActionResult DynamicDropDown()
- {
- return View();
- }
- <body>
- <div>
- <label>Select Bank :</label>
- </div>
- <div>
- <select class="form-control" id="op1">
- <option selected="selected">Select</option>
- </select>
- </div>
- </body>
And in the head section add the following script file.
- <script src="~/Scripts/jquery-2.1.4.js"></script>
If you forget to add this jQuery script file then the code doesn't work.
Step 3
In the third step we do an Ajax call, so when the page is loaded only the dropdown list highlighted with data is coming from the database.
To do Ajax call we need to write the following code in the head section.
- < script > $(document).ready(function()
- {
- $.ajax({
- url: "Home/GetData",
- datatype: "JSON",
- type: "Get",
- success: function(data) {
- debugger;
- for (var i = 0; i < data.length; i++) {
- var opt = new Option(data[i].Bname);
- $("#op1").append(opt);
- }
- }
- });
- }); < /script>
Hear GetData is a method that is defined under Controller Home. This method is basically used for the purpose to get the data from the database. Don't worry about this method I will define it in next step.
Here in the preceding Ajax call inside “success: function()” I used the append method of jQuery to append the data to HTML dropdown list; “op1” is the id of our dropdownlist .
Step 4
In step 4 we need to define this GetData() method under our home controller and this method returns a JSON type of data.
Note
Before adding the GetData() method first add a class under model with one property named as BankDetails .
Add the following code inside it:
- Public Class BankDetails
- {
- Public string Bname
- {
- get;
- set;
- }
- }
Just write the code as it is and only make change in the database connection part.
- public JsonResult GetData()
- {
- List < BankDetails > lstBank = new List < BankDetails > (); //Hear we Create BankDetails class type list which we defines inside model.
- con = new SqlConnection("User Id=sa;Password=focus123;Database=SURYADB;Data Source=FOCUS-DEV-0001\\SQLSERVER2012"); // Write your DB connection .
- //cmd = new SqlCommand("select * from IBank", con);
- DataSet ds = new DataSet();
- da = new SqlDataAdapter("select * from IBank", con);
- da.Fill(ds);
- for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
- {
- BankDetails ba = new BankDetails();
- ba.Bname = ds.Tables[0].Rows[i]["sBName"].ToString();
- lstBank.Add(ba);
- }
- return Json(lstBank, JsonRequestBehavior.AllowGet);
- }
For your reference I have given you complete code once again. Just understand it and use it as it is, don't forget to add the jQuery file v 2.1 (the latest one or better) and add the model namespace inside the controller.
In the Model folder add the class called BankDetails and add the following code:
- Public string Bname {get; set;}
- public ActionResult DynamicDropDown() {
- return View();
- }
- public JsonResult GetData() {
- List < BankDetails > lstBank = new List < BankDetails > ();
- con = new SqlConnection("User Id=sa;Password=focus123;Database=SURYADB;Data Source=FOCUS-DEV-0001\\SQLSERVER2012");
- //cmd = new SqlCommand("select * from IBank", con);
- DataSet ds = new DataSet();
- da = new SqlDataAdapter("select * from IBank", con);
- da.Fill(ds);
- for (int i = 0; i < ds.Tables[0].Rows.Count; i++) {
- BankDetails ba = new BankDetails();
- ba.Bname = ds.Tables[0].Rows[i]["sBName"].ToString();
- lstBank.Add(ba);
- }
- return Json(lstBank, JsonRequestBehavior.AllowGet);
- }
- <head>
- <script src="~/Scripts/jquery-2.1.4.js"></script>
- <script>
- $(document).ready(function () {
- $.ajax({
- url: "Focus8/GetData",
- datatype: "JSON",
- type: "Get",
- success: function (data) {
- debugger;
- for(var i=0;i
- <data.length;i++)
- {
- var opt = new Option(data[i].Bname);
- $("#op1").append(opt);
- }
- }
- });
- });
- </script>
- </head>
- <body>
- <div>
- <label>Select Bank :</label>
- </div>
- <div>
- <select class="form-control" id="op1">
- <option selected="selected">Select</option>
- </select>
- </div>
- </body>
If you get an error, mention it in the comments section.
I hope this article will help you, don't forget to send me your suggestion that would help me in improving myself.
Manoj KumarPosted Mar 22, 2022, 6:25 AM
Good One...
Susil PadhiPosted Aug 22, 2015, 11:46 PM
Nice article my friend
Jaipal ReddyPosted Aug 16, 2015, 4:02 AM
Good Start
Santhakumar MunuswamyPosted Aug 16, 2015, 2:21 AM
Nice Article. Thanks for sharing
Sibeesh VenuPosted Aug 15, 2015, 4:38 AM
Nice Share :)
Sandeep KumarPosted Aug 14, 2015, 10:10 PM
NIce Article Sir :)
Shridhar SharmaPosted Aug 14, 2015, 2:35 PM
good one.
Pankaj Kumar ChoudharyPosted Aug 14, 2015, 12:49 PM
Nice Start Suryakant........
RakeshPosted Aug 14, 2015, 10:54 AM
Good one
Gowtham KPosted Aug 14, 2015, 9:09 AM
Nice Share:)
Gopi ChandPosted Aug 14, 2015, 7:42 AM
Nice work
Karthikeyan KPosted Aug 14, 2015, 7:15 AM
Good start... thanks for sharing
Rajeesh MenothPosted Aug 14, 2015, 7:14 AM
Welcome to c-sharp community..nice share
Upendra Pratap ShahiPosted Aug 14, 2015, 7:14 AM
nice..