Wednesday, 1 May 2013

Filtring via ajax for cities List based on Countries List Selection using Jquery and webservice

------------------------------------------------------------------------
SQL DB
-------------------------------------------------------------------------
CREATE TABLE Countries (

id  int ,

country varchar(50)

)

CREATE TABLE cities (

id  int ,

city varchar(50),

country_id int

)

insert into Countries (id, country) values (1,'INDIA')

insert into Countries(id, country) values (1,'Saudi Arabia')

insert into cities(id, city, country_id) values(1, 'Washington',1)

insert into cities(id, city, country_id) values(2, 'New York',1)

insert into cities(id, city, country_id) values(3, 'Chicago',1)

insert into cities(id, city, country_id) values(4, 'Riyadh',2)

insert into cities(id, city, country_id) values(6, 'Mecca',2)

--------------------------------------------------------------------------
.aspx
--------------------------------------------------------------------------
<div>
        Address: <asp:DropDownList ID="ddlCountries" runat="server" >
        </asp:DropDownList>
   

        <asp:DropDownList ID="ddlCities" runat="server">
            <asp:ListItem Text="You must select country" Value="0"></asp:ListItem>
        </asp:DropDownList>
      
        <span id="loading" style="display:none;">Loading,,</span>
</div>

------------------------------------------------------------------------
.cs
------------------------------------------------------------------------

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string connectionstr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
        SqlDataAdapter da = new SqlDataAdapter("select * from countries", connectionstr);
        DataTable dt = new DataTable();
        da.Fill(dt);

        ddlCountries.DataSource = dt;
        ddlCountries.DataTextField = "country";
        ddlCountries.DataValueField = "id";
        ddlCountries.DataBind();
        //Insert defualt item that's:
        ddlCountries.Items.Insert(0, new ListItem("Select Country,,", "0"));
    }
}