我在 ASP.NET MVC 中创建了一个 Web 应用程序,并尝试通过 Javascript AJAX 调用 Controller 。在 Jquery 中,我们可以发送一个 json 对象,MVC 模型绑定(bind)器会自动尝试创建一个 .NET 对象并作为参数传入 Controller 。
但是,我正在使用无法使用 jquery 的网络 worker 。所以我通过 vanilla xmlhttprequest 对象进行 AJAX 调用。有没有办法通过这种方法发送 Json 对象?
我使用了 xmlhttprequest 的 send 方法,但模型对象在 Controller 中为 null :(
最佳答案
您应该能够使用 JSON2 对其进行字符串化并设置 Content-Type
标题到 application/json
当你发帖时。
http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js
你会做这样的事情:
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));
关于javascript - 如何将 Json 对象(或字符串数据)从 Javascript xmlhttprequest 发送到 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6055714/