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.

1

2 Answers 2

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) {
            }
        });
    }
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.