【问题标题】:jQuery Ajax returning undefined from controller action methodjQuery Ajax 从控制器操作方法返回未定义
【发布时间】:2021-10-09 09:50:07
【问题描述】:

在我的 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 个“未定义”。

【问题讨论】:

  • 结果行似乎没有 Text 属性。您需要检查返回 json。
  • 可能跑题了:你的 url 应该是 url: '/GetLocations/1', 而不是 url: '/GetLocations,,因为你将 id 作为数据传递,所以无论区域如何,它都将始终是 1。跨度>
  • 我怀疑序列化程序使用 camelCase。试试append('&lt;option value="' + location.value + '"&gt;' + location.text + '&lt;/option&gt;');
  • "它有 Text" ... "它适用于 text" - 这些不一样 - 这是为什么我们要求查看实际值,而不是只信守诺言。
  • 我编辑了@Izzy 答案以添加此信息。你能接受他的回答吗?

标签: javascript c# jquery json asp.net-core


【解决方案1】:

我怀疑序列化程序使用 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));
                    });
            });
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-13
    • 2014-07-27
    • 2012-10-20
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多