I'm trying to update a second dropdown list based on the selection of the first dropdown list using Ajax. It appears to be working, I've stepped through the code and selectedId is updating with the correct Id, however the dropdown list itself is not updating. So I think I've missed something somewhere, I need to update the #modelDropDown I think in the success function but not sure how to do it.
jQuery/Ajax:
$('#manufacturerDropDown').change(function () {
var selected = $(this).val();
$.ajax({
url: '/Home/Index',
data: { id: $('#manufacturerDropDown option:selected').val() },
type: "post",
cache: false,
success: function () {
},
error: function () {
}
});
});
Controller Method
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(),
}
}
Previous question for context: Master/Detail dropdown filtering using Lambda in ASP.NET
Edit:
I've gotten closer with the jQuery below, the html is loaded, I can see it in the error log but the console returns the error Uncaught TypeError: Cannot use 'in' operator to search for 'length' in <!DOCTYPE html>.
$('#manufacturerDropDown').change(function () {
var selected = $(this).val();
$.ajax({
url: '/Home/Index',
data: { id: $('#manufacturerDropDown option:selected').val() },
type: "post",
cache: false,
success: function (result) {
alert(result);
var modelDropDown = $('#modelDropDown');
modelDropDown.empty();
$.each(result, function () {
modelDropDown.append(
$('<option>', {
value: this.Value
}).text(this.Text)
);
});
},
error: function () {
}
});
});
Response from Ajax call
Cache-Control: no-cache, no-store
Content-Type: text/html; charset=utf-8
Date: Mon, 08 Jul 2019 23:28:54 GMT
Persistent-Auth: true
Pragma: no-cache
Server: Microsoft-IIS/10.0
Transfer-Encoding: chunked
X-Powered-By: ASP.NET
$.each(result, function () {line. The alert that pops up withalert(result)also returns the entire html page.