如何使用Jquery更新强类型的Html.DropDownList

我有一个带有两个radiobuttons和下拉列表的网页,如下所示:

Course

下拉列表是强类型的,并使用Model.CourseList填充(注意 – 在第一页加载时,’Beginner’是默认选择,下拉列表相应地显示初学者课程选项)

我想要做的是根据选择的单选按钮更新DropDownList,即如果选择“高级”,则在下拉列表中显示一个课程选项列表,如果选择“初学者”,则显示另一个课程列表。

编辑 – 在下面发布我自己的答案,以显示对我有用的解决方案(最后!)

继续返回您的selectlistitem集合; 这很好地转换为JSOn,至少它应该是一个看起来像{text:“a”,value:“1”}的对象数组,你可以循环遍历数组并以这种方式重新创建列表……

所以它适用于强类型对象。 您只需要获取对象并构建基础下拉列表的元素。

HTH。

我想调用的代码位于我的Controller中:

 public ActionResult UpdateDropDown(string courseType) { IDropDownList dropdownlistRepository = new DropDownListRepository(); IEnumerable courseList = dropdownlistRepository.GetCourseList(courseType); return Json(courseList); } 

使用jQuery in Action中提供的示例,我现在有以下jQuery代码:

 $('.radiobuttons input:radio').click(function() { var courseType = $(this).val(); //Get selected courseType from radiobutton var dropdownList = $("#CourseSelection"); //Ref for dropdownlist $.post("/ByCourse/UpdateDropDown", { courseType: courseType }, function(data) { $(dropdownList).loadSelect(data); }); }); 

loadSelect函数直接取自本书,如下所示:

 (function($) { $.fn.emptySelect = function() { return this.each(function() { if (this.tagName == 'SELECT') this.options.length = 0; }); } $.fn.loadSelect = function(optionsDataArray) { return this.emptySelect().each(function() { if (this.tagName == 'SELECT') { var selectElement = this; $.each(optionsDataArray, function(index, optionData) { var option = new Option(optionData.Text, optionData.Value); if ($.browser.msie) { selectElement.add(option); } else { selectElement.add(option, null); } }); } }); } })(jQuery);