Alan Alan - 4 months ago 18
AngularJS Question

Pass Array of Objects in http Post

I have a web api developed. I need to pass an array of objects

[{"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"}]


The model class of web api is given below

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


and the code corresponding to post method in controller file is given below

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


I send the http post request in my js script given below

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


It does not add the above array. Please help me

Answer

the problem is here:

[ResponseType(typeof(Locate))]
public async Task<IHttpActionResult> PostLocate(Locate locate)

and you are posting an array so it should be:

[ResponseType(typeof(Locate))]
public async Task<IHttpActionResult> PostLocate(List<Locate> locates)
Comments