使用Ajax在ASP.NET Core中更新下拉列表

3
我将尝试使用Ajax根据第一个下拉列表的选择更新第二个下拉列表。它似乎正在工作,我已经逐步执行了代码并更新了正确的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(),
    }
}

为了更好的理解上下文,以下是之前的问题:ASP.NET中使用Lambda实现主/从下拉筛选

编辑: 使用下面的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

可能是 在MVC中加载2个下拉列表的更好方法 的重复问题。 - Arthur S.
请提供一下结果快照(服务器响应),你之所以出现错误是因为你试图查看不完全是集合的响应内容。我相信你离解决方案很近了,如果你向我们展示ajax调用的响应内容,我们可以帮助你解决问题。 - Himanshu Pant
感谢 @HimanshuPant。错误日志似乎返回整个HTML页面,并具体抱怨$. each(result,function(){}行。弹出与alert(result)一起弹出的警报也会返回整个HTML页面。 - MM1010
@HimanshuPant 我也在问题中添加了来自开发工具的响应。 - MM1010
1个回答

1

好的,根据我们在评论中的对话和我初步的评估,看起来该操作方法返回的是HTML而不是序列化JSON对象的集合。此外,我不太清楚制造商和型号的结构是什么样子的,因此我将提供类似数据的示例,您可以根据自己的类进行调整。

//This is my ViewModel
public class Model {
    public string Value {get;set;}
    public string Text {get;set;}
    public string ManufacturerID {get;set;}
}

将您的控制器更改为这样做。
public IActionResult Index(string id)
{
    //You will have to update the structure of data according to you viemodel.
    //Also apply you logic for database lookup
    var ModelCollection = _ctx.Models.Where(mdl => mdl.ManufacturerID == id).ToList();
    return Ok(ModelCollection);
}

然后你需要将ajax调用更改为以下内容。
$('#manufacturerDropDown').change(function () {
    var selected = $(this).val();
    $.ajax({
        url: '/Home/Index',
        data: { id: $('#manufacturerDropDown option:selected').val() },
        type: "post",
        cache: false,
    }).done(function(data){
            var modelDropDown = $('#modelDropDown');
            modelDropDown.empty();
            $.each(data["ModelCollection"], function (index, model) {
                modelDropDown.append(
                    $('<option>', {
                        value: model.Value
                    }).text(model.Text)
                );
            });
    }).fail(function(error){
        //Do something with the error response 
    });
});

希望这有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接