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

后端 未结 3 1935
别跟我提以往
别跟我提以往 2020-12-16 13:28

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

3条回答
  •  执念已碎
    2020-12-16 13:37

    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));
    

提交回复
热议问题