Reputation: 81
Been struggling to find a solution to this one, despite the mass of useful information out there.
I have the following Javascript Function that is sending an AJAX call to my controller.
var ajax = new XMLHttpRequest();
var posts = document.getElementsByClassName('postLink');
var sendstr = "";
for (var i = 0; i < posts.length; i++) {
sendstr += ',';
sendstr += posts[i].attributes.getNamedItem('onmouseup').value.substr(9, 1);
}
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
var posts = JSON.parse(ajax.responseText);
addPostToList(posts.Title, posts.Description, posts.postID);
}
}
ajax.open('POST', '@Url.Action("SAR", "posts")', true);
ajax.setRequestHeader('Content-type', 'text/plain');
ajax.setRequestHeader('Content-length', sendstr.length);
ajax.setRequestHeader('Connection', 'close');
ajax.send(encodeURIComponent(sendstr));
The controller is as follows...
[HttpPost]
public ActionResult SAR(string r)
{
var s = Request.QueryString[0];
return Content(Post.JSONSerialize());
}
I have tried a number of different Data types as the Parameter and have still not received anything of use... I have also tried Request.Param, request.queryString, request.Form and a number of other 'solutions' that i have found on the web, it is passing only a comma seperated list of integers to the controller, stored as a string. How do i read this value when it has been sent off to the controller?
~I do not want a JQuery or JS Framework solution, i would like a native Javascript solution.
Upvotes: 2
Views: 6252
Reputation: 1873
1.- Use JSON as your content-type.
2.- The string you are sending back has to match the parameter name you are expecting on your controller.
change your sendstr to the following format:
//Where r is the name of your parameter on the controller.
var sendstr = '{"r":"STRING YOU WANT TO RETURN"}';
then change your ajax configuration to be
ajax.open('POST', '@Url.Action("SAR","Controller")', true);
ajax.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
ajax.setRequestHeader('Content-Length', sendstr.length);
ajax.send(sendstr);
I hope this works for you :)
Upvotes: 7