Bind DropDownList using Jquery Ajax in Asp.net
Jquery Ajax Code to Bind dropdownlist in asp.net
Introduction : In this article i will show you how to bind a DropDownList to avoid page refresh via a webmethod .It is very useful and many time we require to use Jquery ajax . I have here provided html and c# code behind code to understand Jquery Ajax in asp.net .
Jquery Ajax Code to Bind dropdownlist in asp.net
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "AjaxInJquery.aspx/GetCityData",
dataType: "json",
success: ajaxSucceess,
error: ajaxError
});
function ajaxSucceess(response) {
$.each(response.d, function (key, value) {
$("#ddlCategory").append($("<option></option>").val(value.CityId).html(value.Cityname));
});
}
function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
</script>
Html Code DropDownList
<asp:DropDownList ID="ddlCategory" runat="server"> </asp:DropDownList>C# Code for binding Dropdownlist using Jquery Ajax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;
using System.Data.SqlClient;
public partial class AjaxInJquery : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List GetCityData()
{
List CityCollection = new List();
try
{
DataSet Ds = GetDataSet("Select * from Countrytable");
CityCollection = Ds.Tables[0].AsEnumerable().Select(data => new City() { CityId = (int)data["CountryID"], Cityname = (string)data["CountryName"] }).ToList();
}
catch (Exception) { }
return CityCollection;
}
public static DataSet GetDataSet(string Query)
{
DataSet Ds = new DataSet();
try
{
string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
SqlConnection Con = new SqlConnection(strCon);
SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
Da.Fill(Ds);
}
catch (Exception) { }
return Ds;
}
}
public class City
{
public int CityId { get; set; }
public string Cityname { get; set; }
}
if i m using same in asp.net when click on button it automatically page refresh and reload initial value .for this what to do?please give response........
ReplyDelete