Hi rakeshkuma,
Add HiddenField and set the valuein DropDownList change.
Then inside Ajax success set the selected value from DropDownList.
Refer below code.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
<asp:DropDownList ID="ddlCustomers" runat="server">
</asp:DropDownList>
<asp:HiddenField ID="hfCountry" runat="server" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type='text/javascript'>
$(function () {
BindDropDownList();
$('[id*=ddlCustomers]').on('change', function () {
$('[id*=hfCountry]').val($(this).find('option:selected').val());
});
})
setInterval(function () {
BindDropDownList();
}, 2000);
function BindDropDownList() {
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var ddlCustomers = $("[id*=ddlCustomers]");
ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if ($('[id*=hfCountry]').val() != "") {
$(ddlCustomers).val($('[id*=hfCountry]').val());
}
}
});
}
</script>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Code
C#
[WebMethod]
public static List<ListItem> GetCustomers()
{
string query = "SELECT Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
List<ListItem> customers = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
customers.Add(new ListItem()
{
Value = sdr["Country"].ToString(),
Text = sdr["Country"].ToString()
});
}
con.Close();
return customers;
}
}
}
VB.Net
<WebMethod>
Public Shared Function GetCustomers() As List(Of ListItem)
Dim query As String = "SELECT Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
Dim customers As List(Of ListItem) = New List(Of ListItem)()
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(New ListItem() With {
.Value = sdr("Country").ToString(),
.Text = sdr("Country").ToString()
})
End While
End Using
con.Close()
Return customers
End Using
End Using
End Function