I'm currently facing an issue with the DropDownGroupList extension for ASP.NET MVC 5. My goal is to dynamically populate the control using JavaScript and data from an AJAX request. I've managed to achieve this for the DropDownList control, but I'm struggling to replicate the same functionality for the DropDownGroupList. Here's a snippet of my code for the DropDownList - how can I adapt this for the other control?
$("#Area").change(function () {
$("#Station").empty();
$("#Station").prop("disabled", true);
if ($("#Area").val() != "Select area") {
var AreaOptions = {};
AreaOptions.url = "/Production/SelectArea";
AreaOptions.type = "POST";
AreaOptions.data = JSON.stringify({ Area: $("#Area").val() });
AreaOptions.datatype = "json";
AreaOptions.contentType = "application/json";
AreaOptions.success = function (LinesList) {
$("#Line").empty();
$("#Line").append("<option value='Select line'>Select line</option>");
for (var i = 0; i < LinesList.length; i++) {
$("#Line").append("<option value=" + LinesList[i].Value + ">" + LinesList[i].Text + "</option>");
}
$("#Line").prop("disabled", false);
$("#Station").prop("disabled", true);
};
AreaOptions.error = function () { alert("No data for selected area!"); };
$.ajax(AreaOptions);
}
else {
$("#Line").empty();
$("#Line").prop("disabled", true);
}
});
Edit 1
Here's my controller where I attempted to return a JsonResult:
public JsonResult SelectLine()
{
List<GroupedSelectListItem> Stations = new List<GroupedSelectListItem>();
Stations.Add(new GroupedSelectListItem { Text = "Station 1", Value = "Station 1", GroupName = "Line 1", GroupKey = "Line 1" });
Stations.Add(new GroupedSelectListItem { Text = "Station 2", Value = "Station 2", GroupName = "Line 1", GroupKey = "Line 1" });
Stations.Add(new GroupedSelectListItem { Text = "Station 3", Value = "Station 3", GroupName = "Line 2", GroupKey = "Line 2" });
Stations.Add(new GroupedSelectListItem { Text = "Station 4", Value = "Station 4", GroupName = "Line 3", GroupKey = "Line 3" });
Stations.Add(new GroupedSelectListItem { Text = "Station 5", Value = "Station 5", GroupName = "Line 4", GroupKey = "Line 4" });
return Json(Stations);
}
How can I bind this data to a DropDownGroupList?
Edit 2
Stephen Muecke's solution worked perfectly. Thank you!