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

标签 c# asp.net ajax asp.net-mvc

我正在尝试使用 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 () {
        }
    });
});

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(),
    }
}

上一个上下文问题: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

最佳答案

好的,根据我们在评论中的对话和我的初步评估。看起来操作方法正在为您拥有的对象集合返回 html 而不是序列化的 json。另外我真的不知道Manufacturers和Models的结构是什么,所以我将做一个类似数据的例子,你可以根据你的类进行调整。

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

更改您的 Controller 以执行此操作。

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 
    });
});

希望这对您有所帮助!

关于c# - 在 ASP.NET Core 中使用 Ajax 更新下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943095/

相关文章:

asp.net - MVC 中不包含 'GetEnumerator' 的公共(public)定义

c# - 如何从文件夹读取文本文件并将其转换为 MySQL 中的表

javascript - AJAX 中的 onreadystatechange 不起作用

c# - 将两个 DateTime 对象相加

C# 中来自 SQL Server 的 JavaScript 数组数据

c# - 如何集成 Expression<Func<>> 来清理我的 Linq-to-Entity 查询?

ajax - 通过 ajax 加载更多帖子后,Masonry View 无法正常工作

javascript - 使用 HTML/PHP/AJAX 将行插入数据库

c# - 中等信任度的 NHibernate 2.1.2

c# - 使用 Sha256 散列字符串