Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

Sending data to MVC Action via jQuery ajax, parameter is null

I've gone through several questions here related to this, and so far none of them have fixed my particular issue. I'm sending data related to the selected rows in a DataGrid to an action on the server using ajax. The JavaScript code looks like this:

function addSelected() {
        var grid = $("#optionsGrid").dxDataGrid("instance");
        var gridData = grid.getSelectedRowsData();

        $.ajax({
            type: "POST",
            url: "/api/Options/AddRange",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ data: gridData })
        });
    }

And the action on the server (for now):

[HttpPost("api/[controller]/[action]")] 
public async Task<IActionResult> AddRange(string data)
{

    return Ok();
}

I've inspected it in a browser and the gridData value is definitely populated with the data I want before being sent to the server, and the action is hit, but the 'data' parameter is always null. I also tried putting the [FromBody] attribute on the parameter but it didn't change it. No matter what I name the data or whether or not I stringify it the parameter is null.

Changing the datatype to dynamic didn't help either, it was still null. The data needing to be sent is also included in the Request body upon inspection.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this way

function addSelected() {
    var grid = $("#optionsGrid").dxDataGrid("instance");
    var gridData = grid.getSelectedRowsData();

    $.ajax({
        type: "POST",
        url: "/api/Options/AddRange?data=" + JSON.stringify(gridData),
        contentType: "application/json; charset=utf-8"
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...