Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am am filling a dropdown using Ajax

$(document).ready(function() {

    var ID = $("#ID").val();

    fillDropdown(ID); //fills the dropdown via an $.ajax call

    var anotherID = @Model.AnotherID;

    //alert(anotherID);
    $("#AnotherID").val(anotherID); //try to set the selected value

});

The dropdown is defined in the page as:

@Html.DropDownListFor(x => x.AnotherID, Enumerable.Empty<SelectListItem>())

The line to set the selected value of the dropdown is: $("#AnotherID").val(anotherID);

and it only works if I uncomment the alert just above!

Any ideas why?

share|improve this question

1 Answer

up vote 1 down vote accepted

Ajax calls are asynchronous . You have to set the selected value after the Ajax call completes. The alert is buying you time... That's why it works with the alert. If you are using jquery the add an onsuccess callback and set the selected value within the callback.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.