JSON 数据在 ASP.NET 核心 MVC 应用程序中使用 ajax JQuery 呈现后返回为未定义

JSON data is returned as undefined after rendered using ajax JQuery in ASP.NET Core MVC app

Please click here to see the debugged result and rendered data image

我正在 ASP.NET 核心 MVC 应用程序中开发一个函数,每次我单击下拉列表项时,它都会根据项目的 ID 呈现相应的数据。

这是我在控制器中的动作

// this function get list of course and render a dropdown list of courses.
public async Task<IActionResult> Index()
{
    List<SelectListItem> listItem = new List<SelectListItem>();
    var courses = await _context.Course.ToListAsync();

    foreach (var course in courses)
    {
        listItem.Add(new SelectListItem { Text = course.CourseName, Value = course.CourseId.ToString() });
    }

    ViewBag.CourseList = listItem;
    return View();
}

这是一个 returns 部分视图作为 JSON 数据的功能,该数据取决于课程的 ID。

[HttpGet]
public async Task<IActionResult> GetNoteById(int id)
{
    var noteModel = await _context.Course
                                  .Include(n => n.Notices)
                                  .AsNoTracking()
                                  .FirstOrDefaultAsync(m => m.CourseId == id);

    if (noteModel == null)
        return Json(new { data = NotFound(), message = "Error while retrieving data." });

    return Json(noteModel);
}

这是我的 .cshtml 文件

// some code ....

<div class="col-sm-4 offset-4 form-inline">
    <label class="">Courses </label>
    <select id="courses_dropdown_list" class="custom-select ml-2"
            asp-items="@(new SelectList(ViewBag.CourseList, "Value","Text") )">
    </select>
</div>

// some code ...

<table class="table table-striped table-bordered" style="width:100%;">
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>File Type</th>
                <th>File</th>
                <th>Created On</th>
            </tr>
        </thead>
        <tbody id="note_table">

          // partial view will be loaded in here 
        </tbody>
</table>

最后,这是我的 ajax 脚本,可帮助呈现 JSON 数据。

<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $("#courses_dropdown_list").change(function () {
        var id = $("#courses_dropdown_list").val();
        var noteTable = $("#note_table");
        var result = "";
        $.ajax({
            cache: false,
            type: "GET",
            url: "@Url.Action("GetNoteById", "Note")",
            datatype: "json",
            data: { "id": id },
            success: function (data) {
                noteTable.html("");
                $.each(data, function (id, note) {
                    /* this is what I tried to debug 
                    there is no problem with the data 
                    but when it is renderd, it returned undefined */

                    console.log(id);
                    console.log(note);

                    result += `
                        <tr>
                            <td>${note.Id}</td>
                            <td>
                                <a href="/note/NoteDetail/${note.Id}" class="nav-link mt-0">${note.Name}</a>
                            </td>
                            <td>
                                <a href="/note/DowloadNoteFromDB/${note.Id}" class="nav-link mt-0">###</a>
                            </td>
                            <td>{note.FileType}</td>
                            <td>{note.CreatedOn}</td>
                        </tr>`
                });
                noteTable.html(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("failed to load data.");
            }
        });
    });
});

当我单击下拉列表项时,table 按我的预期呈现。但是,每列中的数据返回为 undefined。我尝试使用 console.log(id)console.log(note) 进行调试,以检查 idnote 在 ajax 函数中传递的是否正常。但是返回的数据是可以的,没有问题。希望有人能帮帮我!

$.each(data, function (item) {
                        /* this is what I tried to debug 
                        there is no problem with the data 
                        but when it is renderd, it returned undefined */

                        

                        result += `
                            <tr>
                                <td>${item.courseId}</td>
                                <td>
                                    <a href="/note/NoteDetail/${item.courseId}" class="nav-link mt-0">${item.courseName}</a>
                                </td>
                                <td>
                                    <a href="/note/DowloadNoteFromDB/${item.courseId}" class="nav-link mt-0">###</a>
                                </td>
                                <td>{item.fileType}</td>
                                <td>{item.createdOn}</td>
                            </tr>`
                    });

您需要将函数更改为:

            $.each(data.notices, function (id, note) {

            result += `
                <tr>
                    <td>${note.id}</td>
                    <td>
                        <a href="/note/NoteDetail/${note.id}" class="nav-link mt-0">${note.name}</a>
                    </td>
                    <td>
                        <a href="/note/DowloadNoteFromDB/${note.id}" class="nav-link mt-0">###</a>
                    </td>
                    <td>{note.fileType}</td>
                    <td>{note.createdOn}</td>
                </tr>`
        });

测试结果: