0

我正在点击控制器,但是当我回到 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
                        }));
                    });
                });
            }
            });
4

1 回答 1

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);

}

于 2013-03-18T04:36:30.987 回答