i'm currently learning asp.net core MVC and when i tried to post data using jquery ajax i got this error
Failed to load resource: the server responded with a status of 400 ()
here is my controller :
[HttpPost]
public async Task<IActionResult> PostOrders([FromBody] OrderDetailModel model)
{
try
{
foreach (var ord in model.Items)
{
var orderDetail = new OrderDetail()
{
ItemId = ord.ItemId,
Quantity = ord.Quantity
};
_db.OrderDetails.Add(orderDetail);
}
await _db.SaveChangesAsync();
return Json(new { success = true, message = "Orders created successfully" });
}
catch (Exception ex)
{
return BadRequest(new { message = ex.Message });
}
}
My jquery :
var itemId = $("#itemDropdown").val();
var itemName = $("#itemDropdown option:selected").text();
var quantity = $("#quantity").val();
var selectedItem = {
itemId: parseInt(itemId),
itemName: itemName,
quantity: parseInt(quantity)
};
$("#submitButton").click(function () {
event.preventDefault();
var data = {
items : selectedItems
}
console.log(data);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Orders/PostOrders",
processData: true,
cache: false,
dataType: "json",
data: JSON.stringify(data),
error: function (jqXHR) {
console.log(jqXHR);
}
});
})
i tried debugging it, the error was in the line
await _db.SaveChangesAsync();
when it triggers the catch badrequest, any idea why it throws an error? is it because of the await ?
Thanks in advance!