【问题标题】:AJAX Passing JSON to Controller as String Returns NullAJAX 将 JSON 作为字符串传递给控制器​​返回 Null
【发布时间】:2017-05-11 15:55:48
【问题描述】:

我有以下 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();
    }     

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

【问题讨论】:

    标签: javascript json ajax asp.net-mvc


    【解决方案1】:

    你发送数据

      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" })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多