首页 > 解决方案 > jQuery Ajax 从控制器操作方法返回未定义

问题描述

在我的 ASP.NET Core 3.1 应用程序中,我正在使用 jQuery 实现级联 DropDown 功能。第一个 DropDown (Region) 的值更改应填充第二个 DropDown,位置。更改 ddlRegion 的值时,jQuery 正确地点击了 Controller 方法并且还在 json 列表中返回了结果,但是第二个 DropDown 中的结果被填充为“未定义”。

[下拉 HTML]

   <table style="margin-left:2%;margin-top:2%">
        <tr style="width:200px">
            <td style="width:100px">Region</td>
            <td style="width:300px">
                @Html.DropDownList("DDLRegion", new List<SelectListItem>
        {
           new SelectListItem{ Text="-- Select --", Value = "0" },
           new SelectListItem{ Text="North", Value = "1" },
           new SelectListItem{ Text="South", Value = "2" },
           new SelectListItem{ Text="All", Value = "3" }
        }, new { @id = "DDLRegion" })

            </td>
            <td style="width:100px">Location</td>
            <td style="width:300px">
                @Html.DropDownList("DDLLocation", new List<SelectListItem>
                {
                   new SelectListItem{ Text="-- Select --", Value = "0" },
                   }, new { @id = "DDLLocation" })
            </td>
        </tr>
</table>

[jQuery代码]

$(document).ready(function () { $("#DDLRegion").change(function () {

        $("#DDLLocation").empty();
            $.ajax({

                type: 'GET',

                url: '/GetLocations/1',
                dataType: 'json',
                data: { id: $("#DDLRegion").val() },

                success: function (locationsList) {

                    $.each(locationsList, function (i,location) {

                        $('#DDLLocation').append('<option value="'
                            + location.Value + '">' +
                            location.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve locations');
                }
            });
            return false;
        })
});

[控制器代码]

   [Route("~/GetLocations/{id}")]
    public JsonResult GetLocations(string id)
    {
        List<SelectListItem> locations =
                    new List<SelectListItem>();

        int counter = 0;
        string line;

        locations.Add(new SelectListItem
        {
            Text = "Select",
            Value = "0"
        });

        switch (id)
        {
            case "1":
                // Read the file and display it line by line.  
                System.IO.StreamReader file =
                    new System.IO.StreamReader(@"North_Locations.txt");
                while ((line = file.ReadLine()) != null)
                {
                    locations.Add(new SelectListItem { Text = line, Value = counter.ToString() });
                    counter++;
                }

                file.Close();
                counter = 0;
                line = "";

                break;
            case "2":

                // Read the file and display it line by line.  
                System.IO.StreamReader file2 =
                    new System.IO.StreamReader(@"South_Locations.txt");
                while ((line = file2.ReadLine()) != null)
                {
                    locations.Add(new SelectListItem { Text = line, Value = counter.ToString() });
                    counter++;
                }

                file2.Close();
                counter = 0;
                line = "";
                break;
         }

        return Json(new SelectList(locations,
                        "Value", "Text"));
    }
}

在 jQuery 代码中,“位置”是未定义的。如果控制器返回 80 个项目,则位置下拉列表将填充 80 个“未定义”。

标签: javascriptc#jqueryjsonasp.net-core

解决方案


我怀疑序列化程序使用 camelCase。当您探索 ajax 成功的结果时,第一个字母需要很小。

您也可以简化您的方法并返回SelectListItem您的回复。因此,您的操作将类似于:

public IActionResult GetLocations(string id)
{
    //you will change the below to match your code
    var locations = new List<SelectListItem>
    {
         new SelectListItem("First Value", "1"),
         new SelectListItem("Second Value", "2"),
         new SelectListItem("Third Value", "3"),
    };

    return Json(locations);
}

我已经使用了getJSON

$(document).ready(function () {

    var url = '@Url.Action("GetLocations", "Home")';
    var location = $('#DDLLocation');

    $("#DDLRegion").change(function() {
        var id = $(this).val();
        $.getJSON(url, { id: id }, function(response) {
                location.empty();
                $.each(response,
                    function(index, item) {
                        location.append($('<option></option>').text(item.text).val(item.value));
                    });
            });
    });
});

推荐阅读