0

I've written the below. Checking the dev tools, I can see that the correct HTML is in the response except it's not loading into the page. No errors appear in the console.

$('#manufacturerDropDown').change(function () {
    var selected = $(this).val();
    $.ajax({
        url: '/Home/Index',
        data: { id: $('#manufacturerDropDown option:selected').val() },
        type: "post",
        cache: false,
        success: function (data) {
            alert(data);
            var modelDropDown = $('#modelDropDown');
            modelDropDown.empty();

            $(modelDropDown).each(function (index, item) {
                modelDropDown.append(
                    $('<option>', {
                        value: item.value,
                        text: item.text
                    }));
            });
        },
        error: function () {
            alert(xhr.status);
            alert(thrownError);
        }
    });
});

What am I missing?

EDIT:

Here's the response HTML, I've omitted header and footer:

<form method="post">
    <div class="container">
        <div class="row pt-3">
            <div class="col border bg-light pt-4">
                <div class="form-group row">
                    <label class="col-sm-5 col-form-label text-right" for="ManufacturerId">Manufacturers</label>
                    <div class="col-sm-7">
                        <select class="form-control form-control-sm w-50" id="manufacturerDropDown" value="ManufacturerId" data-val="true" data-val-required="The ManufacturerId field is required." name="ManufacturerId">
                            <option value="217ca128-b8b8-e311-b74d-005056b12c30">F</option>
                            <option value="227ca128-b8b8-e311-b74d-005056b12c30">Audi</option>
                            <option value="237ca128-b8b8-e311-b74d-005056b12c30">BMW</option>
                            <option value="247ca128-b8b8-e311-b74d-005056b12c30">Ford</option>
                            <option value="257ca128-b8b8-e311-b74d-005056b12c30">Mazda</option>
                            <option value="267ca128-b8b8-e311-b74d-005056b12c30">Peugeot</option>
                            <option value="277ca128-b8b8-e311-b74d-005056b12c30">Mercedes</option>
                        </select>
                        <span class="text-danger field-validation-valid" data-valmsg-for="ManufacturerId" data-valmsg-replace="true"></span>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-sm-5 col-form-label text-right" for="ModelId">Models</label>
                    <div class="col-sm-7">
                        <select class="form-control form-control-sm w-50" id="modelDropDown" data-val="true" data-val-required="The ModelId field is required." name="ModelId">
                            <option value="e336de76-90b9-e311-b74d-005056b12c30">Focus</option>
                        </select>
                        <span class="text-danger field-validation-valid" data-valmsg-for="ModelId" data-valmsg-replace="true"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

Here's the code for the controller:

public IActionResult Index(string id)
{
    Guid selectedId = Guid.Parse(id);

    var vm = new HomeViewModel
    {
        Manufacturers = context.ManufacturersTable.OrderBy(x => x.Manufacturer).ToList(),
        Models = context.ModelsTable.OrderBy(x => x.ModelName).Where(x => x.ManufacturerId == selectedId).ToList(),
    }
}
MM1010
  • 591
  • 1
  • 9
  • 26
  • can you add the data exemple? – gandalf Jul 09 '19 at 12:45
  • 2
    You're `each()` doesn't make sense. You are looping over the results of your jQuery lookup, which is an id so only one element, and trying to use data from itself to change itself. You're never using `data` – Taplar Jul 09 '19 at 12:45
  • The problem is not your ajax but your jquery when appending the data. Do a minimal version of the code just appending the data to where you want it to go – Michael Beeson Jul 09 '19 at 12:45
  • Your question is similar to this https://stackoverflow.com/questions/41343215/adding-items-to-a-select-dropdown-via-jquery-is-not-succeeding – gandalf Jul 09 '19 at 12:50
  • Look here also https://stackoverflow.com/questions/56537153/how-to-dynamicly-pass-data-to-select-list/56537592#56537592 – Bosco Jul 09 '19 at 12:51

3 Answers3

0

On the ajax success callback, you are iterating over the dropdown selector. You should iterate over the response data instead:

$('#manufacturerDropDown').change(function () {
    var selected = $(this).val();
    $.ajax({
        url: '/Home/Index',
        data: { id: $('#manufacturerDropDown option:selected').val() },
        type: "post",
        cache: false,
        success: function (data) {
            alert(data);
            var modelDropDown = $('#modelDropDown');
            modelDropDown.empty();

            data.forEach(function (item) {
                modelDropDown.append(
                    $('<option>', {
                        value: item.value,
                        text: item.text
                    }));
            });
        },
        error: function () {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}); 
mgarcia
  • 5,669
  • 3
  • 16
  • 35
  • I get forEach is not a function for this, possible because of the data type? – MM1010 Jul 09 '19 at 13:17
  • What do you mean? I'm using JavaScript array [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method since I'm assuming that what you get in the response is an array. Is that assumption incorrect? In that case, what do you get from the ajax response? – mgarcia Jul 09 '19 at 13:49
0

change for loop to

       for (item in data.Models) { /// or data.property in which actual data is 
         modelDropDown.append(
                $('<option>', {
                    value: item.value,
                    text: item.text
                }));
           }

UPDATE

In controller

public IActionResult Index(string id)
   {
     Guid selectedId = Guid.Parse(id);

var vm = new HomeViewModel
{
    Manufacturers = context.ManufacturersTable.OrderBy(x => 
     x.Manufacturer).ToList(),
    Models = context.ModelsTable.OrderBy(x => x.ModelName).Where(x => 
    x.ManufacturerId == selectedId).ToList(),
   }

  return vm;
}
Satish Patil
  • 438
  • 5
  • 15
0

Try some think like this:

success: function (data) {
            alert(data);
            var modelDropDown = $('#modelDropDown');
            var html="";
            for(var i=0; i<data.length; i++){
                   html+="<option value='"+data[i].value+"'>"+data[i].text+"</option>";
             }
             modelDropDown.html(html);
        }
alexey
  • 783
  • 1
  • 7
  • 19