将通过控制器接收到的JSON保存到数据库MVC



大家好,我从大约4-5天开始使用visual studio,我有很多疑问,多亏了Stack Overflow社区,我获得了更多的知识。我正在尝试将JSON POST到控制器,并使用模型绑定将其保存到数据库中。

我可以使用以下ajax将JSON POST到控制器:

$.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);
**ajaxresult[i] = { "Avatar": object.owner.avatar_url, "Name": object.name, "Score": object.score, "URL": object.url, "Updatedat": object.updated_at };**
});
**var myJSON = JSON.stringify(ajaxresult);**
table.append('</table>');
$('table').replaceWith(table);
debugger;
console.log(myJSON);
$.ajax({
contentType: 'application/json; charset=utf-8',
datatype:'JSON',
type: 'POST',
url: 'http://localhost:60294/Git/Updateto',
**data: myJSON,**
success: function (data) {
alert('Post Succesful');
},
error: function (data) {
alert('error');
}
});
}
});
});

这是我的控制器和型号:

[HttpPost]
public async Task<IActionResult> Updateto(GitJSON gitjson)
{
if (ModelState.IsValid)
{
gitjson.gitdList[0].AvatarURL=;

}
await _context.SaveChangesAsync();
return Ok();
}

型号:

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; }

}
public class GitJSON
{
public List<gitd> gitdList { set; get; }
}

我的理解是,在控制器中,GitJSON模型正在被绑定。因此,JSON对被自动映射到gitd模型的公共成员。

经过研究,我了解到public List<gitd> gitdList { set; get; }

对应于被索引的对象的列表。因此,我假设gitjson.gitdList[0].AvatarURL=;现在指的是我传递的第一个JSON对象的AvatarURL属性。我的理解正确吗?如果为true,我现在如何将JSON保存到数据库中。

此外,如果我把return View();放在Updateto控制器中,我会得到一个500错误。我尚未向Updateto控制器添加视图。这是唯一的原因吗?同样,如果为true,它不应该是一个未找到的错误而不是500错误吗?

我向Updateto控制器添加了一个伪视图,但return view();仍然给出500错误。

  1. 欢迎加入俱乐部MVC
  2. 不能返回不存在的视图,尤其是当客户端期望json响应时
  3. 你需要将你的更改映射到上下文,然后你可以保存它们

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Updateto(GitJSON gitjson)
    {
    try
    {
    if (ModelState.IsValid)
    {
    //here is sample code to map changes to entities
    var gitdIds = gitjson.gitdList.Select(x => x.Id).ToList;
    _context.gitds
    .Where(x => gitdIds.Contains(x.Id))
    .ToList()
    .ForEach(x =>
    {
    //find match data
    var change= data.gitdList.FirstOrDefault(d => d.Id == x.Id);
    //update your fields here
    x.Name = change.Name;
    ...
    });
    //save changes after updated entities
    await _context.SaveChangesAsync();
    }
    return Ok();
    }
    catch (Exception ex)
    {
    return Json(new
    {
    error = ex.Message// or ex.ToString()
    });
    // or return RedirectToPage("Error", ex);
    }
    }
    

最新更新