Home > database >  Can not pass list of object to method by AJAX
Can not pass list of object to method by AJAX

Time:01-14

I'm sorry that this question has been too long. I have consulted a lot of articles on Stack Overflow but it doesn't run on my source code. I am using ASP.NET Core MVC.

My AJAX

        function PayAjax(orders, payment, note) {
        orders = [{ 'id': 1, 'quantity': 2 }, { 'id': 3, 'quantity': 4 }];
        var formData = new FormData();
        formData.append('orders', orders);
        formData.append('payment', payment);
        formData.append('note', note);

        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: '/sale/pay',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (result) {
                var x = 1;
            },
            error: function (error) {
                console.log(error);
            }
        });
    }

My controller

    [HttpPost]
        public async Task<IActionResult> Pay(List<Order> orders, int payment, string note)
        {
                ...
        }
    }

My Object Order

    public class Order
    {
        public int Id { get; set; }
        public int Quantity { set; get; }
    }

My data is coming to controller but I don't access to values.

Orders always have count = 0.

Even if I pass JSON like below, controller orders is always empty

    $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: '/sale/pay',
            type: 'POST',
            data: JSON.stringify({ 'orders': orders, 'payment': payment, 'note': note}),
            processData: false,
            contentType: false,
            success: function (result) {
                var x = 1;
            },
            error: function (error) {
                console.log(error);
            }
        });

CodePudding user response:

Try to put data into formData one by one:

function PayAjax(orders, payment, note) {
        orders = [{ 'id': 1, 'quantity': 2 }, { 'id': 3, 'quantity': 4 }];
        var formData = new FormData();
        for (var i = 0; i < orders.length; i  ) {
                formData.append("orders["   i   "].Id", orders[i].id);
                formData.append("orders["   i   "].Quantity", orders[i].quantity);
            }
        formData.append('payment', payment);
        formData.append('note', note);

        $.ajax({
            dataType: 'json',
            url: '/sale/pay',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (result) {
                var x = 1;
            },
            error: function (error) {
                console.log(error);
            }
        });
    }

CodePudding user response:

You can wrap these parameter request to single object

[HttpPost]
 public async Task<IActionResult> Pay(PayRequest request)

public class PayRequest 
{
  public List<Order> orders {get; set;} 
  public int payment {get; set;}
  public string noteget; set;}
}

CodePudding user response:

you should get parameters by [FromForm] annotation and convert object to FormData if you want post it using formData

public ActionResult Pay([FromForm] List<Order> orders, [FromForm] int payment, [FromForm] string note) { 

}
    function buildFormData(formData, data, parentKey) {
        if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
        Object.keys(data).forEach(key => {
            buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
        });
        } else {
        const value = data == null ? '' : data;

        formData.append(parentKey, value);
        }
    }

    function jsonToFormData(data) {
        const formData = new FormData();
  
        buildFormData(formData, data);
  
        return formData;
    }

    function pay() {
        orders = [{ 'Id': 1, 'Quantity': 2 }, { 'Id': 3, 'Quantity': 4 }];
        PayAjax(orders, 2000, 'Hello')
    }

    function PayAjax(orders, payment, note) {
        const dataToSend = {
            orders,
            payment,
            note
        }

        const data = jsonToFormData(dataToSend)

        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: '/sale/pay',
            type: 'POST',
            data,
            processData: false,
            contentType: false,
            success: function (result) {
                var x = 1;
            },
            error: function (error) {
                console.log(error);
            }
        });
    }
  •  Tags:  
  • Related