我正在尝试将一个JSON数组发送到控制器操作方法,并将其保存到数据库中。
这是控制器:
public class Gitcontroller : Controller
{
public GithubContext _context;
public Gitcontroller(GithubContext context)//the database context
{
_context = context;
}
[HttpPost]
public IActionResult Updateto([FromBody] GitJSON gitjson)
{
try
{
if (ModelState.IsValid)
{
_context.AddRange(gitjson);
_context.SaveChanges();//adding list to table.
}
return View();
}
catch (Exception ex)
{
return RedirectToPage("Error", ex);
}
}
}数据库有一个gitd表。
ajax调用:
$.ajax({
type: 'POST',
url: 'http://localhost:60294/Git/Updateto',
contentType: 'application/json; charset=utf-8',
datatype: 'JSON',
data: obj,
success: function (data) {
alert('Post Succesful');
},
error: function (data) {
alert('error');
}
});型号:
namespace Github.Models
{
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; }
}
} Json:
gitdList: [
{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225? v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},
{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}
]构建是成功的,但是我得到了一个500错误,说加载资源失败。另外,当我在Interactive中运行Updateto时,我得到了以下结果:
> (1,2): error CS0246: The type or namespace name 'HttpPostAttribute'
> could not be found (are you missing a using directive or an assembly
> reference?)
(1,2): error CS0246: The type or namespace name 'HttpPost'
> could not be found (are you missing a using directive or an assembly
> reference?)
(2,17): error CS0246: The type or namespace name
> 'IActionResult' could not be found (are you missing a using directive
> or an assembly reference?)
(2,41): error CS0246: The type or namespace
> name 'FromBodyAttribute' could not be found (are you missing a using
> directive or an assembly reference?)
(2,51): error CS0246: The type or
> namespace name 'GitJSON' could not be found (are you missing a using
> directive or an assembly reference?)
> + additional 6 errors我使用的命名空间:
> using Microsoft.AspNetCore.Mvc; using Github.Models; using System;
> using System.Collections.Generic; using System.Linq; using
> System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering;
> using Microsoft.EntityFrameworkCore;另外,脚手架生成的CRUD操作出现在一个名为gitds的控制器中--它会影响结果吗?我不认为它会影响结果,因为我已经为Gitcontroller定义了一个控制器,view for Gitcontroller action Updateto,并且我还在Gitcontroller中创建了_context。
我如何解决这个问题? 500错误是什么意思?为什么我会得到一个带有编译错误的成功构建。
发布于 2018-07-25 05:10:34
从他的仓库里调出了情报来源。发现与Updateto()方法关联的源不需要的return调用。已推送带有关联更改的PR。
https://github.com/mvermef/.NET/tree/master

https://stackoverflow.com/questions/51463298
复制相似问题