I have a webpage with two radiobuttons and a dropdownlist as follows:
<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 dropdownlist is strongly typed and populated with Model.CourseList (NB - on the first page load, 'Beginner' is the default selection and the dropdown shows the beginner course options accordingly)
What I want to be able to do is to update the DropDownList based on which radiobutton is selected i.e. if 'Advanced' selected then show one list of course options in dropdown, and if 'Beginner' selected then show another list of courses.
The code I would like to call sits within my Controller:
public JsonResult UpdateDropDown(string courseType)
{
IDropDownList dropdownlistRepository = new DropDownListRepository();
IEnumerable<SelectListItem> courseList = dropdownlistRepository.GetCourseList(courseType);
return Json(courseList);
}
Edit - Updated below to show latest position
Using 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 = $(".dropdown"); //Ref for dropdownlist
$.getJSON("/ByCourse/UpdateDropDown", { courseType: courseType }, function(data) {
$(dropdownList).loadSelect(data);
});
});
The loadSelect function is taken straight from the book and is as follows:
(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);
1 day+ later I still cannot get this to work. Assuming the jQuery code is correct then I can only think that the issue is with retrieving the actual data with $getJSON.
I have verified that JsonResult UpdateDropDown does actually retrieve valid data. What am I missing?
Assembly reference? (NB: I have MicrosoftAjax.js and MicrosoftMvcAjax.js in my head tags of the master page
Should JsonResult be ActionResult? (I have seen both used in samples on web)
Do I need to register route Controller/UpdateDropDown in Global.asax?
Any further guidance would be appreciated.