How to send Json object (or string data) from Javascript xmlhttprequest to MVC Controller(如何将 Json 对象(或字符串数据)从 Javascript xmlhttprequest 发送到 MVC 控制器)
问题描述
我在 ASP.NET MVC 中创建了一个 Web 应用程序,并尝试通过 Javascript AJAX 调用控制器.在 Jquery 中,我们可以发送一个 json 对象,MVC 模型绑定器会自动尝试创建一个 .NET 对象并作为参数传入控制器.
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.
但是,我正在使用无法使用 jquery 的网络工作者.所以我通过 vanilla xmlhttprequest 对象进行 AJAX 调用.有没有办法通过这个方法发送Json对象?
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?
我使用了 xmlhttprequest 的 send 方法,但模型对象在控制器中为 null :(
I used the xmlhttprequest's send method but the model object comes as null in the controller :(
推荐答案
您应该能够使用 JSON2 对其进行字符串化并将 Content-Type
标头设置为 application/json
当你发帖时.
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
你会做这样的事情:
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));
这篇关于如何将 Json 对象(或字符串数据)从 Javascript xmlhttprequest 发送到 MVC 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 Json 对象(或字符串数据)从 Javascript xmlhttprequest 发送到 MVC 控制器


基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01