【问题标题】:JSON data is returned as undefined after rendered using ajax JQuery in ASP.NET Core MVC appJSON 数据在 ASP.NET Core MVC 应用程序中使用 ajax JQuery 呈现后返回为未定义
【发布时间】:2021-07-08 02:38:04
【问题描述】:

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

我正在一个 ASP.NET Core 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();
}

这是一个将部分视图作为 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.");
            }
        });
    });
});

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

【问题讨论】:

  • GetNoteById 操作仅返回单个对象 noteModel 而不是集合。但是您正试图在 AJAX 成功中循环通过它。因此,要么从操作方法返回一个集合,要么更改 AJAX 成功以将响应视为单个对象而不是集合。
  • @ChetanRanpariya 不,这个返回的模型包含另一个实例的集合。你可以看到我贴在帖子上的图片。
  • 集合在 noteModel 模型内。所以在 AJAX 成功时,data 将是 nodeModel。并访问您需要循环通过 data.notices 的集合
  • @ChetanRanpariya 如何在 ajax 函数中做到这一点?你能提供一个代码sn-p吗?提前致谢!
  • 尝试将$.each(data, function (id, note) {更改为$.each(data.notices, function (id, note) {

标签: c# ajax asp.net-core-mvc


【解决方案1】:

您需要将您的功能更改为:

            $.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>`
        });

测试结果:

【讨论】:

  • 感谢您花时间和精力测试该功能。因为我的模型Course 包含notices 的集合,并且在每个notices 中都有1 or N further notice,所以我发现我需要遍历data.notices or note 才能访问我需要的数据,并且它有效现在!谢谢!
【解决方案2】:
$.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>`
                    });

【讨论】:

  • 您能否对sn-ps进行更多描述?我有你的方法,但没有奏效。
猜你喜欢
  • 1970-01-01
  • 2022-11-01
  • 2012-04-20
  • 2019-02-07
  • 2022-01-13
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多