级联下拉列表的第二个下拉列表没有填充

时间:2013-03-16 19:33:37

标签: javascript jquery asp.net-mvc-4

我正在点击控制器但是当我回到javascript时,function (courses)函数中嵌入的$.getJSON()被跳过,调试器将转到$.getJSON()函数的末尾,并且第二个下拉列表(课程列表)的数据未填充。我不确定为什么。

这是我的控制器:

public JsonResult GetCourses(int facilityId)
{
    return Json(GetCoursesSelectList(facilityId), JsonRequestBehavior.AllowGet);
}

private SelectList GetCoursesSelectList(int id)
{
    var Courses = db.Courses.Distinct().Where(a => a.FacilityId == id).ToList();
    SelectList list = new SelectList(Courses);
    return list;
}

我的javascript如下:

$("#ddlFacilities").change(function () {
            var selectedFacility = $(this).val();            
            if (selectedFacility !== null && selectedFacility !== '') {
                $.getJSON("/RoundDetail/GetCourses", { FacilityId: selectedFacility },
                    function (courses) {
                    alert(course.Course_Name);
                    var coursesSelect = $('#ddlCourse');
                    coursesSelect.empty();
                    $.each(courses, function (index, course) {
                        coursesSelect.append($('<option/>', {
                            value: course.CourseId,
                            text: course.Course_Name
                        }));
                    });
                });
            }
            });

1 个答案:

答案 0 :(得分:0)

尝试在加载级联下拉列表时查找脚本错误。如果您无法做到,请尝试使用替代方法加载值。我通常按​​照以下方法加载级联下拉列表。

[脚本]

function SetdropDownData(sender, args) {           

        $('#ShipCountry').live('change', function () {
            $.ajax({
                type: 'POST',
                url: 'Home/GetCities',
                data: { Country: $('#ShipCountry').val() },
                dataType: 'json',
                success: function (data) {
                    $('#ShipCity option').remove();
                    $.each(data, function (index, val) {                           
                            var optionTag = $('<option></option>');
                            $(optionTag).val(val.Value).text(val.Text);
                            $('#ShipCity').append(optionTag);

                    });
                }
            });
        });

  }

[控制器]

public IEnumerable<SelectListItem> Cities(string Country)  // ShipCity is filtered based on the ShipCountry value  
    {
        var Cities = new NorthwindDataContext().Orders.Where(c=>c.ShipCountry == Country).Select(s => s.ShipCity).Distinct().ToList();
        List<SelectListItem> type = new List<SelectListItem>();
        foreach (var city in Cities)
        {
            if (city != null)
            {
                SelectListItem item = new SelectListItem() { Text = city.ToString(), Value = city.ToString() };
                type.Add(item);
            }
        }
        return type;
    }
    public ActionResult GetCities(string Country)  
    {
        return Json(Cities(Country), JsonRequestBehavior.AllowGet);

}