1

I want to send array of numbers to my back action and I am getting NULL or error whatever I try. This is my current code.

JS

$.ajax({
        traditional: true,
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        type: "POST",
        data: JSON.stringify(groupIds),
        url: '/Admin/ReadMessages',
        error: function (error) {
            swal.fire({
                title: "Something went wrong. Please try again later.",
                type: "error"
            });
        }
    });

MVC

public ActionResult ReadMessages(List<long> groupIds)
{
     return new HttpStatusCodeResult(HttpStatusCode.OK);
}

Any ideas?

4 Answers 4

2

try this

var arr= new Array();
arr.push(1);
arr.push(2); 

$.ajax({  
    type: "POST",
    url: urlToPost,
    data: JSON.stringify(arr),
    contentType: "application/json"
   });
Sign up to request clarification or add additional context in comments.

2 Comments

U helped me realize what I was doing wrong, error isn't in post it's in my array... Ty
@Serlok exactly I thought about it so I decided to put the array here. so i'm happy to help you ;)
1

Just to clear out for others, as @Amin stated and I realized, error was in sending NON array object, I was using map function and it returned some jquery array, but when I instantiated new Array and sent it, it worked perfectly.

Comments

0
$.ajax({
    traditional: true,
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    type: "POST",
    data: { 'groupIds': groupIds} ,
    url: '/Admin/ReadMessages',
    error: function (error) {
        swal.fire({
            title: "Something went wrong. Please try again later.",
            type: "error"
        });
    }
});

And in Controller :

public ActionResult ReadMessages(IEnumerable<long> groupIds))
{
     return new HttpStatusCodeResult(HttpStatusCode.OK);
}

Comments

0
$.ajax({
    traditional: true,
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    type: "POST",
    data:{groupIds:groupIds},
    url:'@Url.Action("ReadMessages", "Admin")',
    error: function (error) {
        swal.fire({
            title: "Something went wrong. Please try again later.",
            type: "error"
        });
    }
});

controller:

[HttpPost]
public ActionResult ReadMessages(IEnumerable<long> groupIds))
{
     return new HttpStatusCodeResult(HttpStatusCode.OK);
}

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.