我开发了一个web api。我需要传递一个对象数组
[{"Id":"10010","lati":"12.991845763535506","longi":"77.54596710205078","PSID":"1001"},
{"Id":"10011","lati":"12.97846402705198","longi":"77.55729675292969","PSID":"1001"},
{"Id":"10012","lati":"12.967758119178907","longi":"77.54425048828125","PSID":"1001"}]
web api的模型类如下所示
Locate.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace webapi.Models
{
public class Locate
{
[Key][Required]
public string Id { get; set; }
public string lati { get; set; }
public string longi { get; set; }
public string PSID { get; set; }
}
}
和控制器文件中post方法对应的代码如下所示
LocatesController.cs
// POST: api/Locates
[ResponseType(typeof(Locate))]
public async Task<IHttpActionResult> PostLocate(Locate locate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Locates.Add(locate);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (LocateExists(locate.Id))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = locate.Id }, locate);
}
private bool LocateExists(string id)
{
return db.Locates.Count(e => e.Id == id) > 0;
}
我在下面给出的js脚本中发送http post请求
app.js
$scope.adding = function()
{
var idd = $rootScope.vaar;
var datas = [];
var len = latitudes.length;
for (var i = 0; i < len; i++) {
datas.push({
"Id": idd + i.toString(),
"lati": latitudes[i].toString(),
"longi": longitudes[i].toString(),
"PSID": idd
});
}
var jsonData = angular.Json(datas);
var objectToSerialize = {'object':jsonData};
var data = $.param(objectToSerialize);
var config = {
headers: {
'Content-Type': 'application/-www-form-urlencoded;charset=utf-8'
}
}
$http.post('http://localhost:8080/pool/api/locates/', data,config).success(function (data, status, headers, config) {
alert("Success");
}).error(function (data, status, header, config) {
alert("An error has occured while adding!"+status);
});
}
它不会添加上面的数组。请帮帮我
答案 0 :(得分:1)
问题在于:
[ResponseType(typeof(Locate))]
public async Task<IHttpActionResult> PostLocate(Locate locate)
你正在发布一个数组,所以它应该是:
[ResponseType(typeof(Locate))]
public async Task<IHttpActionResult> PostLocate(List<Locate> locates)
答案 1 :(得分:0)
问题解决了。我将参数更改为(List<Locate> locates)
并在post方法中创建了一个逻辑。谢谢Glenn Packer