Friday, September 18, 2009

Country State Ajax binding using ASP.Net

How to bind a State drop down list on change of country drop down list

First we need a to create simple Ajax xmlHttp object and get Which country is selected by using java script. Pass Country to server side Script/page, select all the states with in that country from Data base and pass it to client side using the same xmlHttp
(System.Web.HttpContext.Current.Response.Write("All States"))
server side page name ajaxState.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="StateTableAdapters" %>


<%@ Import Namespace="System.Data" %>


<%
        if (Request.QueryString["Country"] != null)
        {


            String Country = Request.QueryString["Country"].ToString();            StateTableAdapter obpincode = new StateTableAdapter ();nbsp;  DataTableReader Dtr = obpincode.SelectByDt(Country).CreateDataReader() ;


StringBuilder strAllStaters = new StringBuilder();


            strddl.Append(" <select id=selState' style='border: 1px solid DarkBlue; width: 150px;'>");
             strddl.Append("<option value=\"0\">");                strddl.Append("Select One");strddl.Append("</option>");

            while(Dtr.Read()) {strddl.Append("<option value=" + Dtr["Country _Id"].ToString() + ">");
strddl.Append(Dtr["Country "].ToString());strddl.Append("</option>");
}

strddl.Append("</select>");System.Web.HttpContext.Current.Response.Expires = -1;


System.Web.HttpContext.Current.Response.Write(strAllStaters);
>        }


%>
<script type="text/javascript">


function ajaxFunction() {
var xmlHttp;
               try {
xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari


}
               catch (e) { // Internet Explorer


                   try {                       xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");


                   }                   catch (e) {                       try {


                           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                       }                       catch (e) {                           alert("Your browser does not support AJAX!");                           return false;                       }                   }               }               xmlHttp.onreadystatechange = function() {                   if (xmlHttp.readyState == 4) {                       document.getElementById("divState").innerHTML = xmlHttp.responseText;                   }


               }               var OId = 0;


               if (document.getElementById('selCountry’).selectedIndex > 0)                   OId = document.getElementById('selCountry’).value;                              xmlHttp.open("GET", "ajaxState.aspx?CId=" + OId, true);               xmlHttp.send(null);           }</script>
Note:I am setting the respose text to innerHTML of a div (selDiv)
document.getElementById("divState").innerHTML = xmlHttp.responseText;

No comments:

Post a Comment