Код JavaScript:
Код: Выделить всё
const data = [
{
"customer_name": "Abdullah Al Mahmud",
"mobile": 7654,
"bookName": "Physics 1st paper",
"unit_price": 250,
"quantity": 1,
"discount": 0,
"total": 250
},
{
"customer_name": "Abdullah Al Mahmud",
"mobile": 7654,
"bookName": "Physics 1st paper",
"unit_price": 250,
"quantity": 6,
"discount": 0,
"total": 1500
}
];
$.ajax({
url: '/Index',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ data }),
success: function(result) {
console.log(result);
}
});
Код: Выделить всё
public class IndexModel : PageModel
{
[BindProperty]
public List Orders { get; set; }
public async Task OnPostAsync()
{
using (var reader = new System.IO.StreamReader(Request.Body))
{
var body = await reader.ReadToEndAsync();
Orders = JsonConvert.DeserializeObject[*]>(body);
foreach (var order in Orders)
{
System.Diagnostics.Debug.WriteLine($"Customer: {order.CustomerName}, Book: {order.BookName}, Total: {order.Total}");
}
}
return new JsonResult(new { message = "Data received successfully", orders = Orders });
}
}
public class OrderData
{
[JsonProperty("customer_name")]
public string CustomerName { get; set; }
[JsonProperty("mobile")]
public int Mobile { get; set; }
[JsonProperty("bookName")]
public string BookName { get; set; }
[JsonProperty("unit_price")]
public decimal UnitPrice { get; set; }
[JsonProperty("quantity")]
public int Quantity { get; set; }
[JsonProperty("discount")]
public decimal Discount { get; set; }
[JsonProperty("total")]
public decimal Total { get; set; }
}
Что я пробовал:
- Я убедился, что JavaScript отправляет данные в формате JSON.
- Я пробовал читать тело запроса на C# и его десериализацию с помощью JsonConvert.DeserializeObject.
- Я добавил contentType: 'application/json' в запрос AJAX.
Вопрос:
- Что мне здесь не хватает, что может быть причиной ошибки 400?
- Следует ли мне структурировать JavaScript запросить другой вариант или изменить мой код C# для правильной обработки входящих данных?
Будем благодарны за любую помощь!
Подробнее здесь: https://stackoverflow.com/questions/791 ... t-razor-pa