I'm trying to send an object to an api with ajax, how do I solve this issue?

Here is my javascript code:

var order = {

    ClientId: 0,

    products: []


document.querySelector('.btn-order').addEventListener('click', function () 


    var answer = window.confirm("?");

    if (answer) {

        orden.ClientId = document.querySelector('.client').value;




            type: 'POST',

            url: '/Orders/Create1',

            data: JSON.stringify(order),

            contentType: 'application/json; charset=utf-8',

            dataType: 'json',

            success: function (result) {



            error: function (result) {






And this is the controller code:



public ActionResult Create([FromBody]Order order)


    return Json(new { msg = "Success" });


Model classes:

public class Order


    public int ClientId { get; set; }

    public List<ProductsOrder> products { get; set; } 


public class ProductsOrder


    public int ProductId { get; set; }

    public int quantity { get; set; }

    public decimal subtotal { get; set; }


The server is returning an error, this is the browsers response:

POST http://localhost:9019/Orders/Create 500 (Internal Server Error)

send @ jquery.js:9837

ajax @ jquery.js:9434

(anonymous) @ Sell.js:30

1 Answers

Hien Nguyen On
order.ClientId = document.querySelector('.client').value;

You need check document.querySelector('.client').value is number value or not, may be it is string empty or undefiend and when send it to controller. Model Binding can not cast to int value.

The 500 (Internal Server Error) occur at controller action source code. To prevent casting issue, you can change int ClientId to int? ClientId

public class Order
    public int? ClientId { get; set; }
    public List<ProductsOrder> products { get; set; }