Ajax Cascade Dropdownlist

时间:2018-04-28 02:45:59

标签: javascript jquery ajax asynchronous

我正在尝试使用ajax创建级联下拉列表。因此,当用户选择学位下拉菜单时,第二个下拉框显示提供所选学位的学校。但出于某些原因,我的ajax $("#degreeid")。on(" change",function(){});没有被召唤。不知道为什么。求救!

Index.cshtml

@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()

  <div id="select-degree-form">
    <div">
      <span id="Label1">Degree List</span> &nbsp; @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);
  }
}

1 个答案:

答案 0 :(得分:0)

尝试将您的脚本添加到Ionic v1功能:

改变这个:

on ready

为此:

$("#degreeid").on("change", function () {
    showValue($(this).val());
});

并改变这一点:

$(function(){
  $("#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>")
    }
  })
}