简体   繁体   中英

MVC4 and jQuery/AJAX - Error not found when posting JSON

I am using Ajax (and jQuery UI) and when i press a button on the dialog i trigger the following action in the controller:

[HttpPost]
public JsonResult DeletePost(int adrId)
{
   return Json("Hello World Json!", JsonRequestBehavior.DenyGet);
}

My JQuery Code looks like this:

<script type="text/javascript">
$(document).ready(function () {

    $("#dialog").dialog(
        {
            buttons: {
                "Ok": function () {
                    $.ajax({
                        url: '/Home/DeletePost',
                        type: 'POST',
                        data: { adrId: 6 },
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        error: function (xhr) {
                            alert('Error: ' + xhr.statusText);
                        },
                        success: function (result) {
                            CheckIfInvoiceFound(result);
                        },
                        async: true,
                        processData: false
                    });
                    $(this).dialog("close");
                }

            }
        });
    jQuery('.delete').click(function () {

    })
})</script>

However, when i POST to the server, i get an "Error: Not Found"

Try this:

<script type="text/javascript">
$(document).ready(function () {

    $("#dialog").dialog(
        {
            buttons: {
                "Ok": function () {
                    $.ajax({
                       ...
                        data: JSON.stringify({ adrId: 6 }),
                       ...
                    });
                    $(this).dialog("close");
                }

            }
        });
    jQuery('.delete').click(function () {

    })
})</script>

The problem is with your data parameter not being a valid JSON payload.

It is not valid JSON, because jQuery is using the jQuery.param() method internally to prepare the request parameters for typical POST submissions, and it will get converted to the following string:

adrId=6

However, the server is expecting a JSON payload, and what you specified is clearly not a JSON payload. A valid JSON payload would be:

{ 'adrId': 6 }

One approach to send correct JSON in the data parameter is to refactor your jQuery AJAX to look like this:

$.ajax({
    url: '/Home/DeletePost',
    type: 'POST',
    data: "{ 'adrId': 6 }",
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    error: function (xhr) {
        alert('Error: ' + xhr.statusText);
    },
    success: function (result) {
        alert("success");
    },
    async: true,
    processData: false
});

Or you can use JSON.stringify as suggested by others.

An alternative approach would be to send your data as 'application/x-www-form-urlencoded; charset=UTF-8' 'application/x-www-form-urlencoded; charset=UTF-8' which is the default, and that way you don't have to change your data parameter. The code would be much simplified:

$.ajax({
    url: '/Home/DeletePost',
    type: 'POST',
    data: { adrId: 6 },
    error: function (xhr) {
        alert('Error: ' + xhr.statusText);
    },
    success: function (result) {
        alert("success");
    },
    async: true
});

JQuery will recognize that the result is valid JSON.

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