strongmmc strongmmc - 2 months ago 14
jQuery Question

MVC - select correct dropdown option after jquery populating it

I'm creating an editing view that will change its content and form elements based on the editing operations. I pass a model, store a value in a hidden element and then, once the document is ready, i use ajax to populate a dropdown. Immediately after that i need to select the right option that is equal to the value in the hidden element.
My code won't work and i've been trying to figure out why for 2 days.

RAZOR

@Html.DropDownList("ddl_publisher", new List<SelectListItem>(), new { @class = "form-control form-group", @style = "display:none", @onchange = "storeNewPublisher()" });
@Html.Hidden("hid_publisher", Model.Value, new { @class = "form-control" })


JQUERY

$(document).ready(function(){
loadPublishers();
changeDDLSelection();
}

function changeDDLSelection() {
publ = $("#hid_publisher").val();
$("#ddl_publisher").val(publ).change();
}
function storeNewPublisher() {
var publisherText = $("#ddl_publisher option:selected").text();
var publisherValue = $("#ddl_publisher option:selected").val();
var publisherStatus = publisherText.replace(publisherValue, '').replace('-', '').replace('[', '').replace(']', '').trim();
$("#hid_publisher").val(publisherValue);
$("#hid_publisherStatus").val(publisherStatus);
}


AJAX

function loadPublishers() {
$.ajax({
type: "GET",
url: "/Filter/GetPublishers/",
contentType: 'application/json',
data: { productType : $("#ddl_filterProdType option:selected").val() },
success: function (data) {
$.each(data, function (i, pub) {
$("#ddl_publisher").append('<option value="' + pub.Text + '"> [ ' + pub.Value + ' ] - ' + pub.Text + '</option>');
});
},
error: displayPublishFailureMessage
});
}


The call succeedes, and inside changeDDLSelection the variable publ has the right value, but the dropdown won't change its option (it does it, instead, if i execute the code in Chrome console).
Yet, change fires, so storeNewPublisher is triggered but every local variable is undefined.

I can't bang my head on the wall more than this, my neighbours are complaining.

Many thanks in advance

Answer

In your current implementation, you are calling changeDDLSelection method after loadPublishers. But that does not mean that your second method will always execute after changeDDLSelection method finishes all the stuff it had to do. If you put a console.log in each method you will see this.

What you should be doing is, calling the changeDDLSelection method inside the success event of the ajax call for loadPublishers method (after appending all the options from the result array)

function loadPublishers() {
    $.ajax({
        type: "GET",
        url: "/Filter/GetPublishers/",
        contentType: 'application/json',
        data: { productType : $("#ddl_filterProdType option:selected").val() },
        success: function (data) {
            $.each(data, function (i, pub) {
                $("#ddl_publisher").append('<option value="' + pub.Text +
                                   '"> [ ' + pub.Value + ' ] - ' + pub.Text + '</option>');
            });
            //Safely call the second method here
             changeDDLSelection();
         },
         error: displayPublishFailureMessage
     });
}
function changeDDLSelection() {
    var publ = $("#hid_publisher").val();
    $("#ddl_publisher").val(publ).change();
}

$(document).ready(function(){
    loadPublishers();       
}
Comments