How to update strongly typed Html.DropDownList using JQuery
I have a web page with two radio exchanges and a dropdown:
<div class="sectionheader">Course
<div class="dropdown"><%=Html.DropDownList("CourseSelection", Model.CourseList, new { @class = "dropdown" })%> </div>
<div class="radiobuttons"><label><%=Html.RadioButton("CourseType", "Advanced", false )%> Advanced </label></div>
<div class="radiobuttons"><label><%=Html.RadioButton("CourseType", "Beginner", true )%> Beginner </label></div>
</div>
The dropdown is strongly typed and populated with Model.CourseList
(NB - when loading the first page "Beginner" is the default selection and the dropdown lists the options for the beginner course)
What I want to do is update the DropDownList based on which the radio balloon is selected, ie if Advanced is selected then one list of course options will be displayed in the dropdown, and if Novice is selected then show another list of courses.
Edit - posted my own answer below to show the solution that worked for me (finally!)
a source to share
The code I would like to call in my controller:
public ActionResult UpdateDropDown(string courseType)
{
IDropDownList dropdownlistRepository = new DropDownListRepository();
IEnumerable<SelectListItem> courseList = dropdownlistRepository.GetCourseList(courseType);
return Json(courseList);
}
Using the examples provided in jQuery in action , I now have the following jQuery code:
$('.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);
});
});
The function loadSelect
is taken straight from the book and looks like this:
(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);
a source to share
Keep returning your selectlistitem collection; this translates to JSOn nicely, at least it should be like an array of objects that looks like {text: "a", value: "1"} and you can loop through the array and recreate the list that way ...
This way it will work with strongly typed objects. You just need to take objects and build items for the basic dropdown.
NTN.
a source to share