Search code examples
asp.net-mvclistboxjquery-chosendropdowncascadingdropdown

ASP.Net MVC 6 Cascading Dropdowns Not Populating


I'm using cascading dropdowns on a page. The first dropdown is being filled from ViewBag

@Html.DropDownList("OrgGroupID",
                                        (IEnumerable<SelectListItem>)ViewBag.OrgGroups,
                                        new Dictionary<string, object>
                                        {
                                            { "class", "form-control" },
                                            { "width", "100%" },
                                            { "data-placeholder", "Select Group..." },
                                            { "onchange", "groupSelected(this)" }
                                        })

and the second one is being filled when a value is selected from first one. The markup for second dropdown is

@Html.ListBox("Devices",
                            (IEnumerable<SelectListItem>)ViewBag.Devices, 
                                new Dictionary<string, object>
                                {
                                    { "id", "devices"},
                                    { "class", "chosen-select form-control" },
                                    { "width", "100%" },
                                    { "data-placeholder", "Select Devices..." }
                                })  

and the jquery function to fill the second dropdown is

function groupSelected(obj) {            
var selectedGroupId = obj.options[obj.selectedIndex].value;            

$.ajax({
    url: "../Devices/DevicesByGroupId",
    type: "GET",
    dataType: "JSON",
    data: { groupId: selectedGroupId },
    success: function (devicesData) {                                             
        $("#devices").html("");
        $.each(devicesData, function (index, itemData) {                        
            $("#devices").append(
                $("<option></option>").val(itemData.Value).html(itemData.Text)
            );                        
        });
    }
});
}

The api method which is being invoked executes and returns data but for some reason, the values are not appended to the second dropdown.

Please suggest what am I missing here.


Solution

  • @StephenMuecke you saved my day mate! Removing the chose-select class loaded the data. I just found that I had to invoke

    $("#devices").trigger("chosen:updated");
    

    to update the listbox. Thanks a lot for pointing me in this direction :)