ASP.NET MVC5中的级联下拉列表

时间:2016-04-28 21:17:01

标签: javascript c# jquery asp.net ajax

我正在为表单创建两个下拉列表。第一个是区域列表,第二个是根据所选区域过滤到作业类型。

我的大多数代码都基于this answer,但我无法在“视图”中显示“作业类型”列表。我可以看到在调试时附加了正确的选项,但我们仍然坚持为什么它们没有填充“作业类型”下拉列表。

视图

                <!--Area Dropdown-->
                @Html.DropDownList("areas", null , new { @class = "col s12 m6 l3" })

                <!--Job Type Dropdown-->
                @Html.DropDownList("jobType", Enumerable.Empty<SelectListItem>(), "Job Type", new { @class = "col s12 m6 l3" })

控制器代码,填充我的第一个下拉框(区域)

var jobArea = (from a in db.tblJobTypes
                           where a.Active == true
                           select a.Department).Distinct().ToList();
ViewData["areas"] = new SelectList(jobArea);

控制器内的POST操作

    [HttpPost]
    public ActionResult JobTypeByArea(string area)
    {

        var test = (from a in db.tblJobTypes
                      where a.Active == true && a.Department == area
                      select new
                      {
                          id = a.JobTypeID,
                          job = a.JobType
                      }).ToList();
        return Json(test, JsonRequestBehavior.AllowGet);
    }

最后,JQuery

$(document).ready(function () {   

$('#areas').change(function () {

    $.ajax({
        url: '/Home/JobTypeByArea',
        type: 'POST',
        data: { area: $(this).val() },
        datatype: 'json',
        success: function (data) {
            var options = '';
            var category = $('#jobType');
            $.each(data, function () {
                options += '<option value="' + this.id + '">' + this.job + '</option>';
            });

            $('#jobType').append(options);
        },
    });
});
});

0 个答案:

没有答案