I am trying to create cascade dropdownlist using ajax. So when user selects the degree dropdown, the second dropdown box displays schools that offer that selected degree. But for some reasons, my ajax $("#degreeid").on("change",function(){}); does not get called. Not sure why. Help please!
Index.cshtml
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div id="select-degree-form">
<div">
<span id="Label1">Degree List</span> @Html.DropDownList("degreeid", (IEnumerable<SelectListItem>)ViewBag.DegreeList, "Select a Degree")
</div>
</div>
<div id="select-school-form">
<div">
<span id="Label1">School List</span><select id="SecondDropdown"></select>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script>
$("#degreeid").on("change", function () {
showValue($(this).val());
});
function showValue(val) {
console.log(val);
$.getJSON('@Url.Action("GetDropdownList", "Home")' + "?value=" + val, function (result) {
$("#SecondDropdown").html(""); // makes select null before filling process
var data = result.data;
for (var i = 0; i < data.length; i++) {
$("#schoollist").append("<option>" + data[i] + "</option>")
}
})
}
</script>
</div>
<!-- MORE CODE -->
HomeController.cs
[HttpGet]
public JsonResult GetDropdownList(int? value)
{
using (DataModel db = new DataModel())
{
var qry = (from a in db.schools where a.degree_id == value && a.active == true
select new
{
institution_id = a.institution_id,
institution_name = b.institution_name
}).Distinct();
List<string> institutionList = new List<string>();
foreach(var item in qry)
{
institutionList.Add(item.institution_name);
}
return Json(new { data = institutionList }, JsonRequestBehavior.AllowGet);
}
}