简体   繁体   中英

AJAX Passing JSON to Controller as String Returns Null

I have the following AJAX call, simplified to try and pin point the problem:

$('#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();

        });

This calls into the following method:

[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();
    }     

However, the JSON the controller receives is null. Why does this happen? I can see in the browser that there is a request payload, with the values I'd expect. 'Window.glbBlue' is a global value, which I also know has been set properly as alerts were used to check its value.

you send data

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

means your action receive two parameter blue and eg2 but you received only one parameter json which is not supplied. For this reason json is null .

you can change public ActionResult submitForm(string json) {} To public ActionResult submitForm(string blue,string eg2) {} .

OR

data: JSON.stringify({json: "something" })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM