Getting empty list when passing data through ajax in asp.net core

Viewed 591

I am sending list data from view to controller through ajax, data is showing correctly, but receiving empty list of object in controller. Here is my Code snippet.

Here is My java script code:-

//Collect Multiple List For Pass To Controller
    $("#btnSubmit").click(function (e) {
        e.preventDefault();
       // NavContinue();

        var _data = [];
        $.each($("#gridTable tbody tr"), function () {
            _data.push({
                ItemDescription: $(this).find('td:eq(1)').find('input').val(),
                ItemCode: $(this).find('td:eq(2)').find('select').val(),
                Quantity: $(this).find('td:eq(3)').find('input').val(),
                
            });
        });

        var data = JSON.stringify({
            abc : _data
        });
        console.log(data);
        $.when(Save(data)).then(function (response) {
            console.log(response);
        }).fail(function (err) {
            console.log(err);
        });
    });

    //After Click Save Button Pass All Data View To Controller For Save Database
    function Save(abc) {
        alert(abc);
        return $.ajax({
             contentType: 'application/json; charset=utf-8',
            //contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            dataType: 'json',
            type: 'POST',
            url: "/controller/save",
            data: abc,
            success: function (result) {
                if (result) {
                    alert(result);
                }
                else {
                    location.reload();
                }
            }
        });
    }

Here my Model:-

 public class abc
    {
        public string ItemDescription { get; set; }
        public int ItemCode { get; set; }
        public int Quantity { get; set; }

    }

here is my controller:-

 [HttpPost]
    public JsonResult save(abc[] model)
    {
        var response = model;
        return Json(true);
    }

If some one helps me, it will be very appreciated

1 Answers

For the model binder to work on the data you send in the AJAX request you need to place the array in the root of the JSON string you send, not within the abc property. Try this:

var data = JSON.stringify(_data);
Related