Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

Thanks for answer this solve my nightmare.

My grid

..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();

<script type="text/javascript">
function onRowSelected(e) {
        id = e.row.cells[0].innerHTML;
        $.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
    }
</script>

my controller

public ActionResult GridSelectionCommand(string id)
{
     //Here i do what ever i need to do
}

Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:

public void SaveEntry(string jsonData)

and my post action in JS looks like:

$.post("/Journal/SaveEntry", { jsonData: JSONstring });

JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON plugin offered at json.org. So:

JSONstring = JSON.stringify(journalEntry);  // journalEntry is my JSON object

So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.


It seems dataType is missed. You may also set contentType just in case. Would you try this version?

$.ajax({
    url: '/Journal/SaveEntry',
    type: 'POST',
    data: JSONstring,
    dataType: 'json',
    contentType: 'application/json; charset=utf-8'
});

Cheers.


Final Answer:

It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.

Actually, make sure youre using the right key name that your serverside code is looking for as well as per Olek's example - ie. if youre code is looking for the variable data then you need to use data as your key. – prodigitalson 6 hours ago

@prodigitalson, that worked. The variable names weren't lining up. Will you post a second answer so I can accept it? Thanks. – Mega Matt 6 hours ago

So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.


the data argument has to be key value pair

$.post("/Journal/SaveEntry", {"JSONString": JSONstring});