【发布时间】:2019-07-08 22:09:00
【问题描述】:
我正在尝试根据使用 Ajax 选择的第一个下拉列表来更新第二个下拉列表。它似乎正在工作,我已经逐步完成了代码,并且 selectedId 正在使用正确的 Id 进行更新,但是下拉列表本身没有更新。所以我想我在某个地方遗漏了一些东西,我需要更新我认为在成功功能中的#modelDropDown,但不知道该怎么做。
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 () {
}
});
});
控制器方法
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(),
}
}
上一个关于上下文的问题:Master/Detail dropdown filtering using Lambda in ASP.NET
编辑:
我已经接近了下面的jQuery,加载了html,我可以在错误日志中看到它,但是控制台返回错误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 () {
}
});
});
来自 Ajax 调用的响应
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
【问题讨论】:
-
您能否提供一个结果(来自服务器的响应)的快照。您收到该错误是因为您试图查看不完全是集合的响应内容。我相信您非常接近您的解决方案,如果您向我们展示 ajax 调用的响应是什么样的,我们可以为您提供帮助。
-
谢谢@HimanshuPant。错误日志似乎返回带有上述错误的整个 html 页面,并专门抱怨
$.each(result, function () {line。以alert(result)弹出的警报也返回整个 html 页面。 -
@HimanshuPant 我也已将开发工具的回复添加到问题中。
标签: c# asp.net ajax asp.net-mvc