I’m trying to send JSON data from JavaScript to my C# code in an ASP.NET Razor Pages project, but I keep getting a “400 Bad Request” error. The goal is to parse and handle the data in the C# backend. Below is my JavaScript and C# code:
JavaScript code:
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);
}
});
C# code:
public class IndexModel : PageModel
{
[BindProperty]
public List<OrderData> Orders { get; set; }
public async Task<IActionResult> OnPostAsync()
{
using (var reader = new System.IO.StreamReader(Request.Body))
{
var body = await reader.ReadToEndAsync();
Orders = JsonConvert.DeserializeObject<List<OrderData>>(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; }
}
In the browser’s network tab, I can see that the request is being sent, but the server responds with a 400 Bad Request.
What I’ve tried:
- I’ve made sure the JavaScript is sending the data as JSON.
- I tried reading the request body in C# and deserializing it using JsonConvert.DeserializeObject.
- I added contentType: ‘application/json’ in the AJAX request.
Potential Issue: I suspect the issue could be related to the way I’m sending the data. In JavaScript, I’m wrapping the array of objects in an object with a data key, but maybe that’s causing issues with how the backend expects the format.
Question:
- What am I missing here that might be causing the 400 Bad Request?
- Should I structure the JavaScript request differently or adjust my C# code to handle the incoming data properly?
Any help would be appreciated!