使下拉列表依赖于 MVC Core 中的另一个下拉列表

Make drop down list dependent on another drop down in MVC Core

这类似于 Drop-down box dependent on the option selected in another drop-down box 提出的问题,除了我想使用 C# class 来保留下拉值列表而不是纯 html。上一个问题中使用的 jQuery 不适用于我正在尝试做的事情。

我希望用户 select 制造车辆,然后让模型列表取决于 selected

C#Class:DropDowns.cs

public static List<SelectListItem> MakeList (string defaultLabel = "---"){

    List<SelectListItem> makeList = new List<SelectListItem>();

    makeList.Add(new SelectListItem {Text="defaultLabel", Value = ""});
    makeList.Add(new SelectListItem {Text="Ford", Value = "Ford"});
    makeList.Add(new SelectListItem {Text="Toyota", Value = "Toyota"});

    return makeList;}

public static List<SelectListItem> ModelList (string defaultLabel = "---"){

    List<SelectListItem> modelList = new List<SelectListItem>();

    modelList.Add(new SelectListItem {Text="defaultLabel", Value = ""});

    //Ford models
    modelList.Add(new SelectListItem {Text="F-150", Value = "F-150"});
    modelList.Add(new SelectListItem {Text="Mustang", Value = "Mustang"});

    //Toyota models
    modelList.Add(new SelectListItem {Text="Rav4", Value = "Rav4"});
    modelList.Add(new SelectListItem {Text="Tundra", Value = "Tundra"});

    return modelList;}

HTML: myView.cshtml

<select name="make" asp-for="Make" asp-items="DropDowns.MakeList()"></select>
<select name="model" asp-for="Model" asp-items="DropDowns.ModelList()"></select>

我不确定是否可以对 asp 项使用 jQuery。也许我需要在我的模型列表中添加 if 语句?

asp-items依赖服务端解析,如果下拉列表动态变化,需要客户端和服务端保持实时交互。所以这个方法是不可能的。您需要使用 jQuery.

当您看到该页面时,asp-items 已被解析为 html。这时候可以通过jQuery.

来改变html
<select name="make" asp-for="Make" asp-items="DropDowns.MakeList()"></select>
<select name="model" asp-for="Model" asp-items="DropDowns.ModelList()"></select>
@section Scripts{ 
<script>
    $(function () {
        let model = $('#Model').children()
        $('#Make').change(function () {
            let make = $(this).val()
            if (make == 'Ford') {
                $('#Model').empty()
                $('#Model').append(model)
                $('#Model option').eq(4).remove()
                $('#Model option').eq(3).remove()
            } else if (make == 'Toyota') {
                $('#Model').empty()
                $('#Model').append(model)
                $('#Model option').eq(2).remove()
                $('#Model option').eq(1).remove()
            }
        })
    })
</script>
}