我只是想理解,我花了几天的时间试图解决POST操作不起作用的问题(使用Web Api和Angular JS)。我考虑了所有的事情,尝试,搜索,我甚至修改了代码一千次。在那之后,我发现当JSON
格式是这样的时候,POST
是工作的:
{"Name":"Test","Age":23}
但是如果我使用JSON.stringify(options.models);
POST操作不起作用,其格式如下:
[{"Name":"Test","Age":23}]
我不明白它们之间有什么不同(不管括号[]
)
为什么第一个有效,而第二个不起作用?
有没有办法让第二种格式起作用?
第二个是JSON数组吗?
JSON.stringify(options.models)
不应该返回JSON格式吗?
类:
public class EmployeesData
{
public EmployeesData() { }
public EmployeesData(int Id, string Name, int Age, int Phone,string Job, string Department)
{ this.ID = Id;
this.Name = Name;
this.Age = Age;
this.Phone = Phone;
this.Job = Job;
this.Department = Department;}
[Required]
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
在WebApi中:
[HttpPost]
[ResponseType(typeof(EmployeesData))]
public async Task<IHttpActionResult> Post([FromBody]EmployeesData employeesData)
{
if (!ModelState.IsValid) {
return BadRequest(ModelState);}
db.Employees.Add(employeesData);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = employeesData.ID }, employeesData);
}
在Angularjs中:
parameterMap: function(options, operation) {
if (operation !== "read") {
console.log(kendo.stringify(options));
console.log(JSON.stringify(options.models)); // Not work because of []
var R = JSON.stringify(options.models).replace(/]|[[]/g, ''); // work I removed []
console.log(operation + R);
return (R);
}
}
}
发布于 2019-03-18 01:30:32
提到的两种格式({"Name":"Test","Age":23}
和[{"Name":"Test","Age":23}]
)都表示两种不同的合同。
第一个只是一个对象,第二个是对象集合。
假设您从angular发送{"Name":"Test","Age":23}
,那么您的Api控制器方法应该如下所示
public void Demo(Test test)
{
///code here
}
测试应该在哪里?
public class Test
{
public string Name {get;set;}
public int Age {get;set;}
}
如果你正在发送{"Name":"Test","Age":23},那么你的控制器应该是这样的
public void Demo(ICollection<Test> test)
{
///code here
}
https://stackoverflow.com/questions/55209757
复制相似问题