我想送JavaScript對象的集合,我的API服務,但是服務器接收空的對象列表!如何將JS對象的集合發送給ASP.NET API服務?
<script>
//Collection
var Collection = function() {
this.count = 0;
this.collection = {};
this.add = function (key, item) {
if (this.collection[key] != undefined)
return undefined;
this.collection[key] = item;
return ++this.count
}
this.remove = function (key) {
if (this.collection[key] == undefined)
return undefined;
delete this.collection[key]
return --this.count
}
this.item = function (key) {
return this.collection[key];
}
this.forEach = function (block) {
for (key in this.collection) {
if (this.collection.hasOwnProperty(key)) {
block(this.collection[key]);
}
}
}
}
// the JavaScript class for food
function foodcls(no,qunt,name, cals, carb, fat, prt,unt) {
this.no = no;
this.qunt = qunt;
this.name = name;
this.cals = cals;
this.carb = carb;
this.fat = fat;
this.prt = prt;
this.unt = unt;
}
// instantiate new obj
var fod = new foodcls(3, 5, 'SomeName', 300, 180, 100, 20, 'Gram');
var fno =333;
var timCol = new Collection();
timCol.add(fno, fod);
var urlpaths = '/api/FoodServ';
$.ajax({
url: urlpaths,
method: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(timCol),
success: function (data) {
// any thing
}
});
</script>
代碼在ASP.NET API:
[HttpPost]
public HttpResponseMessage Post(List<foodcls> fods) // Here fods is empty
{
int rslt=0;
string UserId = "[email protected]";//User.Identity.Name;
List<Foods_Meal_TBL> fooditems = new List<Foods_Meal_TBL>();
if (fods.Count()>0)
{
foreach (foodcls item in fods)
{
Foods_Meal_TBL fooditem = new Foods_Meal_TBL();
fooditem.FoodNo = item.no;
fooditem.Quantity = item.qunt;
fooditem.PersonID = UserId;
fooditems.Add(fooditem);
}
}
rslt = SaveAllItems(fooditems); // rslt Meal No
return Request.CreateResponse(HttpStatusCode.OK, rslt);
}
任何幫助嗎?
只需發送陣列的項目。嘗試做到這一點。並看看它是如何擊中它。 – Casey
您是否從AJAX調用中查看了XHR對象,將您的成功對象更改爲:success:function(data,status,xhr){/ * break here或使用alert */ alert(xhr.responseText);} ..... – nckbrz
@Casey它與陣列工作,但我需要它的收藏,所以我可以通過關鍵 –