Bind Asp.Net DropDownList using jQuery?
In today's post i am going to cover "How to bind dropdown list in asp.net using jquery.?In the previous tutorials i have explained sealed class ,Abstract class ,Ajax call,Ref and Out Keyword,Autoeventwireup Event in Asp.Net etc.
Before moving to the topic I am assuming that you are aware of Jquery Ajax call ,if now please go through this post before moving further - How to call page method using jquery ajax call
Let start with an example of binding countries name to dropdown list.To do that first create a Country table in MS-SQL.
1 2 | < asp:DropDownList ID = "ddlCountries" runat = "server" > </ asp:DropDownList > |
Once above steps has done.Create a webmethod to retrieve the data from table that we create above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | [WebMethod] public static List<listitem> GetCountries() { string sql_query = "SELECT CountryID,CountryName Name FROM tblCountry" ; string conn = ConfigurationManager.ConnectionStrings[ "ConnectionStringName" ].ConnectionString; using (SqlConnection con = new SqlConnection(conn)) { using (SqlCommand cmd = new SqlCommand(sql_query)) { List<listitem> countries = new List<listitem>(); cmd.CommandType = CommandType.Text; cmd.Connection = con; con.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { countries.Add( new ListItem { Value = reader[ "CountryID" ].ToString(), Text = reader[ "CountryName" ].ToString() }); } } con.Close(); return countries; } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <span class= "line-number" ><span><a>1</a></span><span><a>2</a></span><span><a>3</a></span><span><a>4</a></span><span><a>5</a></span><span><a>6</a></span><span><a>7</a></span><span><a>8</a></span><span><a>9</a></span><span><a>10</a></span><span><a>11</a></span><span><a>12</a></span><span><a>13</a></span><span><a>14</a></span><span><a>15</a></span><span><a>16</a></span><span><a>17</a></span><span><a>18</a></span><span><a>19</a></span></span><script type= "text/javascript" > $( function () { $.ajax({ type: "POST" , url: "Countries.aspx/GetCountries" , data: '{}' , contentType: "application/json; charset=utf-8" , dataType: "json" , success: function (r) { var ddlCountries = $( "[id*=ddlCountries]" ); ddlCountries.empty().append( '<option selected="selected" value="0">--Please select--</option>' ); $.each(r.d, function () { ddlCountries.append($( "<option></option>" ).val( this [ 'Value' ]).html( this [ 'Text' ])); }); } }); }); </script> <span class= "cl" ></span> |
Output:
Conclusion
I hope that this article would have helped you in understanding the way to bind DropDownList using jQuery in ASP.NET.Your feedback and constructive contributions are welcome.
Thanks
Bind Asp.Net DropDownList using jQuery?
Reviewed by CodiBucket
on
09:02
Rating:

No comments: