1

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"}]}

1
  • Have you tried adding [FromBody] to the param in the controller? Commented Feb 23, 2022 at 9:41

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks :-) i added [FromBody] and removed {"selectorModels":...}. now im getting the data in my controller.
0

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.

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.