ozz
ozz

Reputation: 5366

Setting selected value of a Select using JQuery from an MVC model property

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?

Upvotes: 1

Views: 2016

Answers (1)

ek_ny
ek_ny

Reputation: 10243

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.

Upvotes: 2

Related Questions