ListboxFor not Binding when dropdown change in Ajax call

345 views Asked by At

I'm trying to load the ListboxFor control when user changes the particular dropdown. Below is the code I tried to achieve it, but it's not working. Can any one guide me? Thanks in advance.

@Html.ListBoxFor(c => c.ClientDemographicHospitalId, new MultiSelectList(Model.Hospitals, "Value", "Text"), new { ng_model = "hospitalDropdownList", @class = "HospitalListbox", style = "width:65%" })
$.ajax({
    url: '/Controller/ActionMethod',
    type: "POST",
    dataType: "JSON",
    data: { clientId: clientId },
    success: function (data) {
        $("#ClientDemographicHospitalId").empty();
        $("#ClientDemographicHospitalId").append($('<option></option>').val(0).html("Select Hospital"));
        $.each(data, function (i, hospitals) {
            $("#ClientDemographicHospitalId").append($('<option></option>').val(hospitals.ClientDemographicHospitalId).html(hospitals.Name));
        });
    }
});
public ActionResult GetHospitalsByClient(int clientId)
{
    JsonResult result = new JsonResult();
    var hospitals = GetHospital(clientId);
    if (hospitals != null)
    {
        result.Data = hospitals.ToList();
        result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }
    return result;
}

enter image description here

1

There are 1 answers

2
Leo On

Maybe you can take a look at the rendered HTML in your browser by inspecting the DOM elements? I think the problem might be around there, also because you are getting the ID from a table I assume, and probably you are getting an ID which is '20932' in the ListBox, and you are trying to call an element with ID #ClientDemographicHospitalId, which probably is different than the one you are pointing at, in that case you should use HospitalListbox class and call the Jquery element like:

$(".HospitalListbox").empty();
$(".HospitalListbox").empty();
$(".HospitalListbox").append($('<option></option>').val(0).html("Select Hospital"));
$.each(data, function (i, hospitals) {
    $(".HospitalListbox").append($('<option></option>').val(hospitals.ClientDemographicHospitalId).html(hospitals.Name));
});

Also inside the success of the AJAX call, put a console.log(data); to see exactly which data you are receiving and want to put in those elements.