javascript - AJAX 将 JSON 作为字符串传递给 Controller ​​返回 Null

标签 javascript json ajax asp.net-mvc

我有以下 AJAX 调用,经过简化以尝试查明问题:

$('#userUpdateForm').submit(function (e) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("submitForm", "Home")',
                data: JSON.stringify({
                    'blue': window.glbBlue,
                    'eg2': 'eg3'
                }),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    alert("Success");
                },
                error: function (result) {
                    alert("A problem occured when submitting the form.");
                }
            });
        e.preventDefault();

        });

这会调用以下方法:

[HttpPost]
    public ActionResult submitForm(string json)
    {
        System.Diagnostics.Debug.WriteLine("made it here");

        var check = System.Web.Helpers.Json.Decode(json);

        System.Diagnostics.Debug.WriteLine(check);
        System.Diagnostics.Debug.WriteLine(check.glbBlue);

        return View();
    }     

但是, Controller 收到的 JSON 为空。为什么会出现这种情况?我可以在浏览器中看到有一个请求负载,其中包含我期望的值。 “Window.glbBlue”是一个全局值,我也知道它已正确设置,因为警报用于检查其值。

最佳答案

您发送数据

  data: JSON.stringify({
                'blue': window.glbBlue,
                'eg2': 'eg3'
            })

表示您的操作收到两个参数 blueeg2,但您只收到一个未提供的参数 json。因此,jsonnull

您可以将 public ActionResult SubmitForm(string json) {} 更改为 public ActionResult SubmitForm(string blue,string eg2) {}

或者

数据:JSON.stringify({json: "something"})

关于javascript - AJAX 将 JSON 作为字符串传递给 Controller ​​返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920377/

相关文章:

ios - AFNetworking 2.0、AFJSONResponseSerializer、AFHTTPResponseSerializer 和并发

ajax - jQuery Ajax - 向 DOM 添加新元素

javascript - 如何清除jquery中的输入文件字段?

javascript - 在 Angular 中更改 CSS 主题

javascript - 检查 json 对象是否存在并保存到本地存储中

php - 如何合并JSON两个索引然后解析信息

javascript - AJAX 以及如何更改地址栏 (?aaa=ggg)

php - 高级搜索页面上的实时 MySQL 搜索结果

javascript - JSON.NET 是做什么用的? MVC已经有一种将对象转换为json的方法

javascript - 使用 Javascript 迭代 JSON 数据