用ajax post array陣列到Mvc web Api後臺接受不到的問題
阿新 • • 發佈:2019-02-11
普通string陣列
$.ajax({ type: "post", url: "http://localhost:8902/api/PriceRatio/Add", data: {"":["123","123","12"]}, dataType: "json", traditional: true, success: function (msg) { } });
[HttpPost]
public bool Add([FromBody]string[] ids)
{
return true;
}
物件陣列:
for (var i = 0; i < 3; i++) { prices.push({ Id:"123", UpdateTime: null, Type: "other", Price: 123, Url: "www", Remark: "demo", }); }; $.ajax({ type: "post", url: "http://localhost:8902/api/PriceRatio/Add", data: { "": prices}, dataType: "json", traditional: false, success: function (msg) { } });
[HttpPost] public bool AddPriceRatios([FromBody]List<PriceRationModel> priceRations) { if (ModelState.IsValid) { return PriceRatioBLL.AddPriceRatios(priceRations) > 0; } else { throw new Exception(BadRequest(ModelState).ModelState.Values.FirstOrDefault()?.Errors.FirstOrDefault()?.ErrorMessage); } }
如果Post是string陣列或者int陣列,則ajax中traditional: true,
如果Post是物件陣列,則ajax中traditional: false,否則物件將為空