Rodrigo Garcia
Rodrigo Garcia

Reputation: 95

MVC3 binding for a json nested array

I have a simple javascript array. it's declared like this:

coords = []

and everytime a user clicks on an image, I do something like this:

coords.push([x,y])

so I end up with something like this: (in javascript)

[[342,144],[477,99],[632,148],[529,162]]

but I don't know what to bind it to in the controller method... I've tried

List<List<int>>, int[][], int[,]

none of them seem to work. It only works when I use string.

This is the code I'm using to send it to the server:

$.ajax({
    type: "POST",
    url: "/home/SaveCoords",
    data: { coords: JSON.stringify(coords) }
}).done(function (msg) {
    alert("Data Saved: " + msg);
});

And this is the code I use on the controller

[HttpPost]
public ActionResult SaveCoords(string coords)
{
    return Json("Hello", JsonRequestBehavior.AllowGet);
}

Help?

Upvotes: 4

Views: 1096

Answers (1)

archil
archil

Reputation: 39491

You should set request content type to application/json, and change data accordingly.

This is the working example:

    $.ajax({
        type: "POST",
        url: "/home/SaveCoords",
        contentType : 'application/json',
        data: JSON.stringify(coords)
    }).done(function (msg) {
        alert("Data Saved: " + msg);
    });

And server

    public ActionResult SaveCoords(int[][] coords)
    {
        return View();
    }

Upvotes: 6

Related Questions