I am looking to cascade the dependent State and City list from drop-down on selecting Country.
So, I select India => Maharashtra => Cities from Maharastra should cascade.
In the Controller I am able to see city list, but same is not returns to ajax success call in jquery.
Data is viewed in controller but not going to the Ajax Success event.
View
$(document).ready(function () {
var noCountry = $("#Country").children("option:selected").text();
if (noCountry != '') {
$('#state').append("<option value='0'>Selet State</option>");
}
$("#Country").change(function () {
var selkt = noCountry;
var selectedCountry = $(this).children("option:selected").text();
$('#state').empty();
$('#state').append("<option value='0'>Selet State</option>");
if (selectedCountry != '') {
$.ajax({
type: 'POST',
url: "/Home/GetStates",
data: { selectedCountry: selectedCountry },
success: function (data) {
if (data && data.length > 0) {
$.each(data, function (i, item) {
$('#state').append(new Option(item.stateName, item.stateId));
});
}
}
});//ajax ends
}
}); //First logik ends here
//Kountry logik starts here
$('#cityList').append("<option value='0'>Select City</option>").text();
$('#state').change(function () {
var stateSelected = $('#state').children("option:selected").text();
if (stateSelected != 'Selet State' | stateSelected != '') {
$.ajax({
type: 'POST',
url: "/Home/GetCity",
data: { stateSelected: stateSelected },
success: function (data)
{
alert("Working")
},
error: function () {
alert("Failed")
}
});//2nd ajax end here
}
}); //2nd logik ends here
});
Controller
[HttpPost]
public JsonResult GetCity(string stateSelected)
{
using (Db db = new Db())
{
State state = db.States.Where(x => x.stateName == stateSelected).FirstOrDefault();
int id = state.stateId;
List<City> data = db.Cities.Where(x => x.stateId == id).ToList();
ViewBag.ID = id;
ViewBag.list = data;
return Json(new {data, JsonRequestBehavior.AllowGet });//cities, JsonRequestBehavior.AllowGet
}
}
Any help is appreciated
Please help with this. Thank you
2
Answers
I run your code with some changes on my system and it works.
View :
you have to fix the action
if you still have some problems try to add dataType to ajax