I am writing a logic to display list of States on selection on Country.
I am using jQuery Ajax for this so that the State list gets updated instantly without reload of page.
I am stuck at place where I am getting the State list for selected Country but not aware to pass the jSon return type in view using ajax. Below is my code
View
<table>
<tbody>
<td>
@Html.DropDownList("countryVal", (IEnumerable<SelectListItem>)ViewBag.countryVal, "Select Country", new { @id = "Country" })
</td>
<td>
<select id="state">Selet State
</select>
</td>
</tbody>
</table>
<script src="~/Scripts/jquery-3.6.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select").change(function () {
var selectedCountry = $(this).children("option:selected").text();
alert(selectedCountry);
if (selectedCountry != '') {
alert("Working")
$('#state').empty();
$.ajax({
type: 'POST',
url: "/Home/GetStates",
data: { selectedCountry: selectedCountry },
success: function (data) {
if (data && data.length > 0) {
$.each(res, function (i, item) {
$('#state').append(new Option(item.stateName, item.stateId));
});
}
}
})
}
});
});
</script>
Controller
public ActionResult DropDown()
{
using (Db db = new Db())
{
ViewBag.countryVal = new SelectList(db.Countries.ToList(), "countryId", "CountryName");
//ViewBag.stateName = new SelectList(db.States.ToList(),"stateId","stateName");
//var test = ViewBag.countryVal;
return View();
}
}
[HttpPost]
public JsonResult GetStates(string selectedCountry)
{
using (Db db = new Db())
{
Country data = db.Countries.Where(x => x.CountryName == selectedCountry).FirstOrDefault();
int id = data.countryId;
List<State> stateList = db.States.Where(x => x.countryId == id).ToList();
ViewBag.ID = id;
ViewBag.SList = stateList;
return Json(stateList, JsonRequestBehavior.AllowGet);
}
}
Any help is much appreciated.
Thank you
2
Answers
Here is the solution and working code for State but Country list not working
So, helped adding a debugger and identify the breaking point.
You don’t need to put the list in the viewbag in Jayson
Suppose state has Name and Id fields