javascript - Setting dropdown value after AJAX call not working - Stack Overflow

I have an ASP.NET MVC application, and one of the pages has dropdowns to select Country and State.Thi

I have an ASP.NET MVC application, and one of the pages has dropdowns to select Country and State. This page collects customer data, including the address.

I followed this tutorial to set it all up so that the State values are populated when the Country is selected.

So, I have it working fine when a new customer is added that the Country drop down is populated, and when you change the value for Country, the State dropdown is refilled, and on submitting the form, I get the StateID and CountryID in the model.

What I'm having problems with is on editing a customer, when the model already has a StateID and CountryID, I can get the Country dropdown to select the correct value, but not the State dropdown.

The FillStates()method below is used to populate the State dropdown when the Country value is changed.

function FillStates() {

   var countryID = $("#CountryID").val();

   $.ajax({
       url: '/Customers/GetStates',
       type: "GET",
       dataType: "JSON",
       data: { CountryID: countryID },
       success: function (states) {
           $("#StateID").html("");
           if (Object.keys(states).length > 0) {
               $("#StateID").append($('<option></option>').val(0).html('Select a State'));
           }
           else {
               $("#StateID").append($('<option></option>').val(0).html(''));
           }

           $.each(states, function (i, state) {
               $("#StateID").append(
                   $('<option></option>').val(state.StateID).html(state.Name));
               });
           }
    });
}

For editing a customer though, I need to fill the States dropdown on page load AND select the correct value from the dropdown.

Here's the javascript that should do exactly that...

$(document).ready(function () {
    $.when(FillStates()).done(function (e) {
        $("#StateID").val('@Model.StateID');                
    });            
});

But this isn't working - I've debugged it and (let's assume the model has StateID = 8) when it hits the line $("#StateID").val('8'); that line executes without error but doesn't change the selected value of the dropdown.

If I were to move that line into the bottom of the FillStates() method, it DOES change the selection properly - but that would then execute every time the Country is changed, instead of only executing once when the page loads.

Why is the exact same line of code $("#StateID").val('8'); working fine when it's inside the FillStates() method, but not working when I execute it after FillStates() pletes?

I have an ASP.NET MVC application, and one of the pages has dropdowns to select Country and State. This page collects customer data, including the address.

I followed this tutorial to set it all up so that the State values are populated when the Country is selected.

So, I have it working fine when a new customer is added that the Country drop down is populated, and when you change the value for Country, the State dropdown is refilled, and on submitting the form, I get the StateID and CountryID in the model.

What I'm having problems with is on editing a customer, when the model already has a StateID and CountryID, I can get the Country dropdown to select the correct value, but not the State dropdown.

The FillStates()method below is used to populate the State dropdown when the Country value is changed.

function FillStates() {

   var countryID = $("#CountryID").val();

   $.ajax({
       url: '/Customers/GetStates',
       type: "GET",
       dataType: "JSON",
       data: { CountryID: countryID },
       success: function (states) {
           $("#StateID").html("");
           if (Object.keys(states).length > 0) {
               $("#StateID").append($('<option></option>').val(0).html('Select a State'));
           }
           else {
               $("#StateID").append($('<option></option>').val(0).html(''));
           }

           $.each(states, function (i, state) {
               $("#StateID").append(
                   $('<option></option>').val(state.StateID).html(state.Name));
               });
           }
    });
}

For editing a customer though, I need to fill the States dropdown on page load AND select the correct value from the dropdown.

Here's the javascript that should do exactly that...

$(document).ready(function () {
    $.when(FillStates()).done(function (e) {
        $("#StateID").val('@Model.StateID');                
    });            
});

But this isn't working - I've debugged it and (let's assume the model has StateID = 8) when it hits the line $("#StateID").val('8'); that line executes without error but doesn't change the selected value of the dropdown.

If I were to move that line into the bottom of the FillStates() method, it DOES change the selection properly - but that would then execute every time the Country is changed, instead of only executing once when the page loads.

Why is the exact same line of code $("#StateID").val('8'); working fine when it's inside the FillStates() method, but not working when I execute it after FillStates() pletes?

Share Improve this question edited Dec 16, 2015 at 18:01 johnny 5 21.1k54 gold badges136 silver badges214 bronze badges asked Dec 16, 2015 at 17:04 JimJim 6,88113 gold badges48 silver badges72 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

The reason it is not working is the code inside your [$when]1 is being executed even before you load your options to the SELECT element. If you put a console.log('something') in both the places, you can see it.

$when expects a promise to be returned by the method passed into it. Your FillState method is not returning a promise. Your code will work if you change your FillStates method to return a promise.

function FillStates() {
    var countryID = $("#CountryID").val();

    return $.ajax({
        // Other code goes here
    });
}

If you do not wish to do that, You can simply pass the state id to the FillStates function and set the selected value there.

function FillStates(stateId) {

   var countryID = $("#CountryID").val();

   $.ajax({
          url: '/Post/GetStates',
          type: "GET",
          dataType: "JSON",
          data: { CountrId: countryID },
          success: function (states) {
             $("#StateID").html("");
             if (Object.keys(states).length > 0) {
                $("#StateID").append($('<option></option>').val(0).html('Select a State'));
             }
             else {
                    $("#StateID").append($('<option></option>').val(0).html(''));
             }

           $.each(states, function (i, state) {
            $("#StateID").append($('<option></option>').val(state.Value).html(state.Text));
           });
          if (stateId != null) {
               $("#StateID").val(stateId);
          }
        }
    });
 }

Then call it with and without the stateId value as needed

FillStates(@Model.StateId); // call it for your edit on page load
FillStates();   // call it When user changes country

You do not need $when in this case.

You need to return the jqXHR object, returned from $.ajax(), from FillStates(), or the $("#StateID").val() will be executed before your select is filled with data.

function FillStates() {
  var countryID = $("#CountryID").val();
  return $.ajax({ ... });
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745531277a4631705.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信