简体   繁体   中英

ListboxFor not Binding when dropdown change in Ajax call

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;
}

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM