【发布时间】:2015-12-28 07:08:05
【问题描述】:
我正在尝试将 JavaScript 对象集合发送到我的 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 = "sam@am.com";//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);
}
有什么帮助吗?
【问题讨论】:
-
只发送数组中的项目。尝试这样做。看看它是如何击中它的。
-
你有没有看过 AJAX 调用中的 XHR 对象,将你的 sucess 对象更改为:success:function(data, status, xhr){/*break here 或使用 alert */ alert( xhr.responseText);}.....
-
@Casey 它与数组一起使用,但我在 Collection 中需要它,所以我可以按键访问它
-
@nixxbb 谢谢,但是我在asp.net api post函数上打了一个断点先检查数据,AJAX调用到达asp.net函数但没有发送数据!
-
不确定集合和 JSON 格式,我总是创建对象 var obj = {key:val} 并将它们添加到数组中。然后我记得在将 JSON 解析为 List 时遇到了一些麻烦,但已经有一段时间了,我想我并不像我想象的那样熟悉你在做什么,抱歉......
标签: javascript c# list asp.net-web-api collections