0

I have the following code that sends JSON objects to a MVC controller through POST, I have no idea why its not working, any suggestions?

JS

    function Update()
    {
        var objects = $(".Classes");
        items = [];
        objects.each(function () {
            items .push({
                "Id": $(this).find(".input").attr('id'),
                "Value": $(this).find(".input2").val()
            });
        });
        $.ajax({
            type: "POST",
            url: "/A/Update",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },

            data: JSON.stringify(items),

            contentType: "application/json",
            dataType: "json",
            success: function (response) {
            }
        });
    }

Model

public class Update{
            public string Id{get;set;}
            public string Value{ get; set; }
        }

Task

[HttpPost("Update")]
        public async Task<JsonResult> Update(IList <Update> items)
        {...}

The task runs but JSON objects never deserialize to the model, I always get items of count 0.

Dav294
  • 1
  • Maybe this helps https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c – VDWWD Jan 11 '20 at 12:21

2 Answers2

1

you must be change your code data:{"items":JSON.stringify(items)} because you must be send Post data name then change code to this code

function Update()
    {
        var objects = $(".Classes");
        items = [];
        objects.each(function () {
            items .push({
                "Id": $(this).find(".input").attr('id'),
                "Value": $(this).find(".input2").val()
            });
        });
        $.ajax({
            type: "POST",
            url: "/A/Update",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },

            data:{"items":JSON.stringify(items)},

            contentType: "application/json",
            dataType: "json",
            success: function (response) {
            }
        });
    }
MBadrian
  • 409
  • 3
  • 10
0

The only change is to use [FromBody] to let model binding system read post data from request body and bind to your object :

public async Task<JsonResult> Update([FromBody]IList<Update> items)
Nan Yu
  • 26,101
  • 9
  • 68
  • 148