Home > database >  POST Javascript array to MVC controller .NET 5.0
POST Javascript array to MVC controller .NET 5.0

Time:02-23

im trying to send some data from my javascript array to my mvc controller. When i debug through im ending in my method public void GetJSArray(List<SelectorModel> selectorModels)

but selectorModels is null.

Here is my model.

public class SelectorModel
    {
        public int ID { get; set; }
        public string Cords { get; set; }
        public string Name { get; set; }
    }

here is my C# code in controller.

 [HttpPost]
        public void GetJSArray(List<SelectorModel> selectorModels)
        {
            //Code here           
        }

and here is my JavaScript/Ajax

function SaveInfoSpots() {
    var savedeSpots = JSON.stringify({ selectorModels: infospots });
    $.ajax({
        type: "POST",
        url: '/Home/GetJSArray',
        contentType: "application/json; charset=utf-8",
        dataType: 'JSON',//json
        data: savedeSpots,
        traditional: true
    });
}

If i make a console.log(savedeSpots) i get this. {"selectorModels":[{"ID":1,"Name":"Infospot1","Cords":"5000.00, 2293.85, 2278.05"},{"ID":1,"Name":"Infospot2","Cords":"1.94, 584.50, 5000.00"},{"ID":1,"Name":"Infospot3","Cords":"5000.00, -2705.97, -277.02"},{"ID":1,"Name":"Infospot4","Cords":"5000.00, 504.93, -2845.93"}]}

CodePudding user response:

Two place need modify in your code:

First, about model binding, add [FromBody] attribute on action parameter:

[HttpPost]
public void GetJSArray([FromBody]List<SelectorModel> selectorModels)
{
    //Code here           
}

Second, your API need an array not an object, so when you call the API, you need post the parameter like this:

[
    {
        "ID": 1,
        "Name": "Infospot1",
        "Cords": "5000.00, 2293.85, 2278.05"
    },
    {
        "ID": 1,
        "Name": "Infospot2",
        "Cords": "1.94, 584.50, 5000.00"
    },
    {
        "ID": 1,
        "Name": "Infospot3",
        "Cords": "5000.00, -2705.97, -277.02"
    },
    {
        "ID": 1,
        "Name": "Infospot4",
        "Cords": "5000.00, 504.93, -2845.93"
    }
]

not the {"selectorModels":...} format.

If you just need APIs, create webapi project is better than mvc project.

CodePudding user response:

Add [FromBody] to your controller list param such as

public void GetJSArray([FromBody] List<SelectorModel> selectorModels)

Try removing

traditional: true

and

 charset=utf-8

from the ajax call as well. Should see the populated list then in the controller.

  • Related