Reputation: 113
I have two dropdownlists for Languages and Countries
On selecting a language in the dropdownlist, should fill corresponding countries in the country dropdownlist
@Html.DropDownList("LanguageSelectList", null, null, new { @class = "hyper-select fixedwidth300"})
@Html.DropDownList("CountrySelectList", null, null, new { @class = "hyper-select fixedwidth300" })
Here is my jquery script
$("#LanguageSelectList").change(function (event) {
$("#languageValidator").hide();
var selectedLanguage = $("#LanguageSelectList").val();
debugger;
//--------
if (selectedLanguage!='') {
var url = '@Url.Action("GetCountryListByLanguage", "Options")';
$.ajax({
type: "POST",
url: url,
data: { selectedLanguage: selectedLanguage },
dataType: "json",
contentType: "application/json; charset=utf-8",
global: false,
async: false,
success: function (data) {
var ddlCountrylist = $("#CountrySelectList");
debugger;
var jsonString =JSON.stringify(data);
//here how to take data from jsonstring to countries dropdownlist
}
});
} else {
alert('no country returnned');
}
//--------------
});
I am able to retrieve the expected list of countries in the json data as given below .Now how do I fill my country dropdownlist.
jsonString="[{\"Selected\":false,\"Text\":\"n/a\",\"Value\":\"\"},{\"Selected\":false,\"Text\":\"China\",\"Value\":\"CN\"},{\"Selected\":false,\"Text\":\"Hong Kong\",\"Value\":\"HK\"},{\"Selected\":false,\"Text\":\"Singapore\",\"Value\":\"SG\"},{\"Selected\":false,\"Text\":\"Taiwan\",\"Value\":\"TW\"}]"
Upvotes: 0
Views: 2154
Reputation: 23
In the success section of your ajax call to the controller method, you can write the below code:
success: function (data) {
$('#CountrySelectList').empty();
$.each(data.agent, function() {
$('#CountrySelectList').append(
$('<option/>', {
value: this.Value,
html: this.Text
})
);
});
}
I have not tested the above code, but I hope this would definitely work
Upvotes: 1
Reputation: 12705
inside your success handler just iterate thru the returned array and add an option to drop down list for each element in the array.
ddlCountrylist.find('option').remove();
$(data).each(function(i,v){
$('<option value='+v.Value+'>'+v.Text+'</option>').appendTo(ddlCountrylist);
});
Upvotes: 0