首页 > 解决方案 > ajax 请求 ASP.NET Core MVC 的未定义结果

问题描述

这是我的上下文类

public class UserInfoContext
{
    private readonly MVCDbContext _db;

    public UserInfoContext(MVCDbContext db)
    {
        _db = db;
    }

    public async Task<List<UserInformation>> GetAll()
    {
        var list = await _db.UserInfo.ToListAsync();
        return list;
    }

这是我的控制器

private UserInfoContext _ui_context;        
    public UserInformationController(UserInfoContext ui_context)
    {
        _ui_context = ui_context;
    }

    // GET: UserInformation
    public IActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public async Task<IActionResult> LoadUserList()
    {
        var list = await _ui_context.GetAll();
        return new JsonResult(list);
    }

这是我的 AJAX 请求

<script>
$(document).ready(function () {

    loadUser();
    function loadUser() {
        $.ajax({
            method: "GET",
            url: "/UserInformation/LoadUserList",  
            data: {},
            dataType: "JSON",
            success: function (data) {       
                var html = '';
                $.each(data, function (key, item) {
                    html += '<tr>';
                    html += '<td>' + item.Id + '</td>';
                    html += '<td>' + item.FirstName + '</td>';
                    html += '<td>' + item.LastName + '</td>';
                    html += '<td>' + item.Location + '</td>';                      
                    html += '</tr>';
                });
                $('#table_user').html(html);
            }
        });
    }

});

这是我得到的结果

我得到“未定义的结果”。

我得到未定义的结果

这是调试器网络选项卡上的日志

我登录调试器

我究竟做错了什么?

标签: asp.net-core-mvcasp.net-ajax

解决方案


问题是您使用的是大写字母。但是您必须使用小写字母 (item.iditem.firstName)

 $.each(data, function (key, item) {
                    html += '<tr>';
                    html += '<td>' + item.id + '</td>';
                    html += '<td>' + item.firstName + '</td>';
                    html += '<td>' + item.lastName + '</td>';
                    html += '<td>' + item.location + '</td>';                      
                    html += '</tr>';
                });

推荐阅读