通过jQuery ajax将数据发送到MVC Action,参数为null [英] Sending data to MVC Action via jQuery ajax, parameter is null

查看:94
本文介绍了通过jQuery ajax将数据发送到MVC Action,参数为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里已经解决了几个与此相关的问题,到目前为止,没有一个问题可以解决我的特定问题.我正在使用ajax将与DataGrid中选定行相关的数据发送到服务器上的操作.JavaScript代码如下所示:

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

我已经在浏览器中对其进行了检查,在将gridData值发送到服务器之前,肯定用我想要的数据填充了该数据,并且执行了操作,但是"data"参数始终为null.我也尝试将[FromBody]属性放在参数上,但没有改变.无论我命名数据还是不对它进行字符串化,参数都为空.

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.

将数据类型更改为动态也无济于事,它仍然为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.

推荐答案

尝试这种方式

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

这篇关于通过jQuery ajax将数据发送到MVC Action,参数为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆