2013-08-07 94 views
2

我有以下的控制器动作:的getJSON来填充下拉列表MVC4

[HttpPost] 
    public ActionResult GetCourseSections(int courseID) 
    { 
     var Sections = dbcontext.CourseSection.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new 
     { 
      sectionID = x.CourseSectionID, 
      sectionTitle = x.Title 
     }); 
     return Json(Sections, JsonRequestBehavior.AllowGet); 
    } 

这将返回我期待的名单。然后我尝试检索该列表使用下面的代码来填充下拉列表:

$.getJSON('@Url.Action("GetCourseSections", "Admin")', 
      function(data) { 
       var courseSectionDropdown = $('#coursesectiondd'); 
       courseSectionDropdown.empty(); 
       courseSectionDropdown.append($('<option/>', { 
        value: 0, 
        text: "Test" 
       })); 
       $.each(data, function (index, data) { 
        courseSectionDropdown.append($('<option/>', { 
         value: data.value, 
         text: data.text 
        })); 
       }); 
      }); 

虽然在调试添加它们添加唯一上榜的项目时,我能看到JSON对象的列表是默认选项“测试“,我正在设置。任何人都可以从我的代码中看到为什么数据没有被读取?有我在的jQuery

回答

0

试试这个..它会工作犯了一个错误......

$.getJSON("@Url.Content("~/Admin/GetCourseSections")", null, function (data) { 
     $('#coursesectiondd').empty(); 
     for (i = 0; i < data.length; i++) {  
       $('#coursesectiondd').append($('<option></option>').text(data[i].sectionTitle).attr('ID', data[i].sectionID)); 
      } 
    }); 
0

它会工作...

function changeSltLeague() { 
    $.getJSON('/league/GetByName', 
     { leagueName: $("#sltLeagueId option:selected").text() }, 
     function (data) { 
      currentLeagueId = data.Id; 
      currentLeague = data.Name; 
      showNextRoundInfo('/round/GetNextRoundOfLeague', data.Id); 
     }); 
} 
$(document).ready(function() { 
    var leagueId = @leagueId; 

    if (leagueId > 0) { 
     $('#sltLeagueId option[value=' + leagueId +']').attr("selected", true); 

     changeSltLeague(); 
    } 

}); 
1

您需要匹配您的jQuery的数据属性与方法中的名称相同:

$.getJSON('@Url.Action("GetCourseSections", "Admin")', null, 
     function(data) { 
      var courseSectionDropdown = $('#coursesectiondd'); 
      courseSectionDropdown.empty(); 
      courseSectionDropdown.append($('<option/>', { 
       value: 0, 
       text: "Test" 
      })); 
      $.each(data, function (index, data) { 
       courseSectionDropdown.append($('<option/>', { 
        value: data.sectionID, 
        text: data.sectionTitle 
       })); 
      }); 
});