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 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
