Ajax fill country state and city without postback in asp.net

Country will be filled on page load and once user will select any country we will fill states from that country and again when user will change state we will fill city for that state without postback ( asynchronously) with the help of update panel in asp.net.

Create three methods to fetch country, state by country and city by state

 CountryRepository.FetchCountries(); to fetch country from database
 StateRepository.FetchStates(Int32 CountryID); // to fetch state for country
 CityRepository.FetchCities(Int32 StateID); // to fetch city for state

I left code detail to get data from database, I know you guys can do it easily.

Now let's adjust our HTML, first we need a script manager to our page to use update panel so add it

<asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel ID="upnlCountry" runat="server" UpdateMode="Conditional">        
    <ContentTemplate>
        <div>
            <asp:DropDownList ID="ddlCountry" runat="server"  
                AutoPostBack="true"
                CssClass="ddl2" 
                OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" />
        </div>
        <div>
            <asp:DropDownList ID="ddlState" runat="server" 
                AutoPostBack="true"
                CssClass="ddl2" 
                OnSelectedIndexChanged="ddlState_SelectedIndexChanged" />
        </div>

        <div>
            <asp:DropDownList ID="ddlCity" runat="server" 
                CssClass="ddl2" />
        </div>
    </ContentTemplate>
</asp:UpdatePanel>

You can notice we added auto postbakc = true to out country and state drop down so it can call our code behing method and keep in an update panel so it will call those methods asynchronously. Now time to add code, so here is the complete code

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlCountry.DataSource = CountryRepository.FetchCountries();
        ddlCountry.DataTextField = "CountryName";
        ddlCountry.DataValueField = "CountryID";
        ddlCountry.DataBind();
        // Add an item to show select country
        ddlCountry.Items.Insert(0, new ListItem("Select Country", "0"));
    }
}

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
    // First clear both state and city drop down
    ddlState.Items.Clear();
    ddlCity.Items.Clear();

    // we will fill state only when any country is selected
    if (Convert.ToInt32(ddlCountry.SelectedValue) > 0)
    {
        ddlState.DataSource = StateRepository.FetchStates(Convert.ToInt32(ddlCountry.SelectedValue));
        ddlState.DataTextField = "StateName";
        ddlState.DataValueField = "StateID";
        ddlState.DataBind();
    }
    // Add an item to show select state
    ddlState.Items.Insert(0, new ListItem("Select State", "0"));
    ddlCity.Items.Insert(0, new ListItem("Select City", "0"));
}

protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
    // First clear city drop down
    ddlCity.Items.Clear();

    // we will fill city only when any state is selected
    if (Convert.ToInt32(ddlState.SelectedValue) > 0)
    {
        ddlCity.DataSource = CityRepository.FetchCities(Convert.ToInt32(ddlState.SelectedValue));
        ddlCity.DataTextField = "CityName";
        ddlCity.DataValueField = "CityID";
        ddlCity.DataBind();
    }
    // Add an item to show select city
    ddlCity.Items.Insert(0, new ListItem("Select City", "0"));
}

We use ddlXXX.Items.Insert(0, new ListItem("Select XXXX", "0")) to add an item at position 0 to show a message to select, and in SelectedIndexChanged event we first check if user is selected the very first item then we are just clearing the next drop down and not calling any method to get data from database because that is not needed.

Hamden Process manager with a reputed organization, Fond of learning new features and technology related to C#, ASP.Net, SQL Server, MVC etc.I like to help others, if I can
  • ajax
  • updatepanel
By Hamden On 04 May, 13  Viewed: 4,791

Other blogs you may like

No action was found on the controller that matches the request

How to post the data from json, in Angularjs $http.post we get this error. why we get this error only when we try to post the json object rather than query string. When we pass the parameter in query string same action method works as it should be. It's a very simple article so we are going to... By Ali Adravi   On 12 Jul 2015  Viewed: 12,055

Using Ajax for Update a View and then Update Data

this blog has been... By Amin Rahdar   On 26 May 2015  Viewed: 218

Ajax Roundedcornersextender padding and margin problem

Ajax Rounded corners extender is used to give corner to any elements like panel and div etc. Most of the time you will need to give the padding to give some space between the border and content, same is used for margin to give some vertical and horizontal space between different controls, but if... By Alicia Gonzalez   On 15 Jun 2013  Viewed: 678

Ajax AsyncFileUpload control example in asp.net to upload only images

Ajax introduced two new controls AsyncFileUpload and SeaDragon, in this article we will see about Asynchronous file upload control, with its different properties and usage. 1. [AsyncFileUpload][1]: by using this control we can upload a file asynchronously (without postback). The file uploading... By Ali Adravi   On 20 May 2013  Viewed: 5,706

Ajax Modalpopupextender show hide from code behind and by javascript

In this article we will discuss different way of show and hide (open and close) modal popup by using Ajax ModalPopupExtender, how to open/close a modal popup from code behind in asp.net or by using JavaScript, how to use multiple buttons to hide the modal popup in asp.net etc. Suppose we have a... By Jonathan King   On 08 Apr 2013  Viewed: 26,346