首页 > 解决方案 > 将 JSON 发送到控制器 MVC 时出现 500 错误

问题描述

我正在尝试将 JSON 数据发送到控制器并使用这些数据来修改数据库。

这是我的ajax调用:

    var ajaxresult = [];
    var table = $('<table>').addClass('table ');
    $('button').on('click', function () {
    $.ajax({
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        type: 'GET',
        url: 'https://api.github.com/search/repositories?q=repos+topic:' + $(this).attr('id') + '&sort=stars&order=desc&per_page=10',
        success: function (data) {

        ajaxresult.push(data);
        debugger;

        table.empty();
        table.append("<thead><tr><th>Avatar</th><th>Name</th><th>Score</th><th>URL</th><th>Updated at</th></tr></thead>");
        $.each(data.items, function (i, object) {

            var row = $('<tr>').addClass('table-primary');
            row.append('<td><img src=' + object.owner.avatar_url + 'height=50px width=50px/></td>');
            row.append('<td>' + object.name + '</td>' + '<td>' + object.score + '</td>' + '<td>' + object.url + '</td>' + '<td>' + object.updated_at + '</td>');
            table.append(row);

        });
        table.append('</table>');
        $('table').replaceWith(table);
    }

   });

  });

$('#save').on('click', function () {
debugger;
$.ajax({

    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    url: 'http://localhost:60294/Git/Updateto',
    data: ajaxresult,
    success: function (data) {
        alert('done');
    },
    error: function (data) {
        alert('error');
    }
});

});

这是我试图向其发布数据的控制器:

[HttpPost]
    public async Task<IActionResult> Updateto(List<gitd> obj,gitd gitd )

    {
        if (ModelState.IsValid)
        {

            foreach (var item in obj)
            {
                item.AvatarURL = gitd.AvatarURL;
                item.Name = gitd.Name;
                item.Score = gitd.Score;
                item.Updatedat = gitd.Updatedat;
            }
            await _context.SaveChangesAsync();
        }

        return View(gitd);

    }

}

这是我想要使用并将数据保存到数据库的模型:

public class gitd
    {
        public int ID { get; set; }
        public string AvatarURL { get; set; }
        public string Name { get; set; }
        public decimal Score { get; set; }
        public DateTime Updatedat { get; set; }

    }

当我使用调试器查看时,每当调用 POST 请求时,我都会收到 500 内部错误。控件直接移动到 ajax 函数的关闭处。在 JQUERY XML 中,我可以看到数据未定义handleobj 未定义,所有发布数据都变为 NULL。我该如何解决这个问题?由于ajaxresult是一个全局变量,#save按钮ajax调用中不应该有json数据吗?为什么数据为NULL。

我还尝试在 POST 请求中提供数据:

 data:{
        "name":"John",
        "age":30,
        "cars":[ "Ford", "BMW", "Fiat" ]
       }

但错误仍然存​​在。

标签: asp.net-mvcvisual-studiomodel-view-controllerentity-framework-6model-binding

解决方案


推荐阅读