asp.net Razor Pages - 根据另一个 select 列表的 selection 更新 select 列表

asp.net Razor Pages - Update select list based on the selection of another select list

我想在用户select另一个select列表中的值时更新select列表。我已经设法获得第一个 select 列表来调用带有参数的模型上的 get(或 post)方法,并且可以更新基础数据。但是第二个 select 列表从不显示新值。

我对 asp.net 不是很有经验,所以我做错了什么?

下面的代码

.cshtml

<div>
    <form method="post">
        <select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
        <select id="destinationStation" asp-items="Model.DestinationStations"></select>
    </form>
</div>


@section Scripts {
<script type="text/javascript">
    function getDestinationStations() {
        var selectedDepartureStationID = $("#departureStation").find(":selected").val();
        console.log("selectedDepartureStationID = " + selectedDepartureStationID);

        $.ajax({
            type: "GET",
            url: "/Index?handler=Departure",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: {
                selectedDepartureStationID: selectedDepartureStationID
            },
            success: function(result) {
                console.log("success - " + result);
            },
            error: function() {
                console.log("failure");
            }
        })
    }
</script>
}

.cs

public List<SelectListItem> DestinationStations
        {
            get
            {
                if (this._selectedDepartureStationID == -1)
                    return new List<SelectListItem>();

                List<Models.Station> stations = new List<Models.Station>();

                List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
                foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
                {
                    List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
                    stations.AddRange(routeSegments2.Select(x => x.Station));
                }

                return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
            }
        }

        public IndexModel(MyViewContext context)
        {
            this._context = context;
        }

        public void OnGet()
        {
            this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
        }

        public IActionResult OnGetDeparture(int selectedDepartureStationID)
        {
            this._selectedDepartureStationID = selectedDepartureStationID;

            return Page();
        }

每当您的#departureStation select 更改时,您的代码将调用 getDestinationStations javascript 代码。如果我理解正确的话,在该功能中,您正在向后端服务器发送请求以接收可能的目的地站。你需要做的是当ajax请求成功时,根据你返回的数组或数据动态添加选项。

我假设你的“/Index?handler=Departure”returns JSON 像:

[
{
    id: 1,
    name: "station1"
},
{
    id: 2,
    name: "station2"
}
]

检查下面的代码是否有效。

$.ajax({
            type: "GET",
            url: "/Index?handler=Departure",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: {
                selectedDepartureStationID: selectedDepartureStationID
            },
            success: function(result) {
                let destinationStationSelect = $('#destinationStationSelect');
                let optionTemplate = $('<option></option>');
                $.each(result, (index, element) => {
                  let option = optionTemplate.clone();
                  option.append(element.name);
                  option.attr('value', element.id);
                  destinationStationSelect.append(option);
                });
            },
            error: function() {
                console.log("failure");
            }
        })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>