简体   繁体   中英

Pass json from js to controller

Data doesn't passing to controller, always null

My script in view:

function deleteRecords() {
    var selected = [];
    $('#myTable input:checked').each(function () {
        selected.push($(this).attr('id'));
    });

    $.ajax({
        url: '/Home/DeleteRecords',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: { "json": JSON.stringify(selected) },
        error: function () {
            alert("Error!");
        }
    });
}

My home controller method:

[HttpPost]
public IActionResult DeleteRecords(string AllId)
{
    return null;
}

send ajax request data like below,

$.ajax({
    url: '/Home/DeleteRecords',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(selected),
    error: function () {
        alert("Error!");
    }
});

and receive the data in action like

[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
    return null;
}

It need to pass the action. Hope it helps to you.

Name your property in the Post the same as your method so that the automatic binding picks it up. - Turns out this doesn't matter for single object.

The data Object you were creating was not parse-able by .net, use JSON.stringify directly for the data payload.

Note: The change in Home controller since you are passing an array of string.

function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
    selected.push($(this).attr('id'));
});

$.ajax({
    url: '/Home/DeleteRecords',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(selected),
    error: function () {
        alert("Error!");
    }
});

}

For your home controller method:

[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
    return null;
}

with the code in your question, try below to get the json

System.Web.Context.Current.Request.Form["json"]

if you want some more graceful stuff, you need to put FromBody attribute in your parameter signature

DeleteResults([FromBody] string 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