2013-03-16 130 views
0

我点击了控制器,但是当我回到javascript时,嵌入$.getJSON()函数的function (courses)函数被跳过,调试器跳到$.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

使用浏览器的开发工具(例如:萤火虫),并检查你得到了什么错误,当请求时间... – 2013-03-16 19:35:37

+0

我在Chrome中使用浏览器开发工具。请求时间是什么意思? – MTL323 2013-03-16 19:36:45

+0

您的JSON调用返回错误(失败),因此它跳过成功方法。检查chrome控制台中的网络/ XHR。 – 2013-03-16 19:37:04

回答

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

}

相关问题