Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Json object (or string data) from Javascript xmlhttprequest to MVC Controller

I created a web application in ASP.NET MVC and trying to call a controller through Javascript AJAX. In Jquery we can send a json object which MVC Model Binder automatically tries to create a .NET object and pass in the controller as an argument.

However I am using a web workers in which jquery cannot be used. So I am making the AJAX call through the vanilla xmlhttprequest object. Is there a a way to send the Json object through this method?

I used the xmlhttprequest's send method but the model object comes as null in the controller :(

like image 995
ganeshran Avatar asked May 19 '11 08:05

ganeshran


People also ask

How pass JSON data in MVC?

1) Create an attribute that overrides the OnActionExecuting event handler. 3) use attribute parameters to figure out the type of object you want to stream the data into. 4) deserialize the JSON object into your object.


1 Answers

You should just be able to use JSON2 to stringify it and set the Content-Type header to application/json when you do the post.

http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js

You would do something like:

var xhr = new XMLHttpRequest();
xhr.open('POST', '/Controller/Action');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
}
xhr.send(JSON.stringify(myData));
like image 94
David Avatar answered Sep 23 '22 19:09

David