Aman
Aman

Reputation: 997

Fetching Cities dynamically in Asp.net HTML control

I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax

<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>

<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>

<script type="text/javascript">
        $('#ddCountry').on('change', function () {

            var storeData = { countryId: this.value }

            $.ajax({
                type: "POST",
                url: "UserRegistration.aspx/GetCities",
                data: JSON.stringify(storeData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert("The data in list is "+data);
                },
                error: error
            });
        });
    </script>

My method on .cs page is as follows:

[WebMethod]
        public static List<CityBO> GetCities(string countryId)
        {
             //returning cities
        }

The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so

ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.

Upvotes: 2

Views: 821

Answers (2)

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14614

You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.

success: function (data) {
    fillDropDown(data.d);
}

function fillDropDown(data){
    var html = "";
    for (var i = 0; i < data.length; i++)
    {
          html += "<option value='" + data[i].ValueField+ "'>" + 
                   data[i].TextField+ "</option>";
    }
     $("select[id$=ddlCity]").html(html);
}

Upvotes: 2

BOBIN JOSEPH
BOBIN JOSEPH

Reputation: 1022

You can use ajax success function given below.

success: function (data) 
{
 var lankanListArray = JSON.parse(data.d);
 // running a loop
 $.each(lankanListArray, function (index, value) 
 {
  $("#ddlCity").append($("<option></option>").val(this.name).html(this.value));              
 });
}

Upvotes: 1

Related Questions