【问题标题】:Null parameter in controller from ajax来自ajax的控制器中的空参数
【发布时间】:2017-07-06 10:20:30
【问题描述】:

当用户单击保存按钮时,JavaScript 函数使用 AJAX 调用控制器并发送有关对象的 JSON 数据。

JavaScript 函数

$.ajax({
        url: "/Data/sendFridgeItems?items=" + JSON.stringify($scope.items.data),
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });

控制器

[HttpPost]
    public ActionResult SendFridgeItems(string items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items);
        foreach (fridge item in fridgeItems)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }

它有效,但我认为通过 url 参数发送数据的方式在我的情况下是不正确的,因为数据会足够大。我想知道是否有更好的方法将我的数据发送到控制器?

我尝试用这种方式发送,但控制器接收到空值。

$.ajax({
        url: "/Data/sendFridgeItems",
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });

$scope.items.data 的 JSON

[{"id":2,"name":"Item1","count":2,"type":"pcs.","purchased":"12/09/2017","wasted":"15/10/2017","cam":"Freezer","comment":"no comment","$$hashKey":"object:38"},{"id":3,"name":"Item2","count":30,"type":"g.","purchased":"15/01/1880","wasted":"21/03/1882","cam":"Cooler","comment":"commented","$$hashKey":"object:39"}]

$scope.items

$scope.items = {
    "count": 2,
    "data": [
      {
          "name": "Item1",
          "count": 2,
          "type": "pcs.",
          "purchased": "12/09/2017",
          "wasted": "15/10/2017",
          "cam": "Freezer",
          "comment": "no comment"
      },
  {
          "name": "Item2",
          "count": 30,
          "type": "g.",
          "purchased": "15/01/1880",
          "wasted": "21/03/1882",
          "cam": "Cooler",
          "comment": "Commented"
      }
    ]
};

N.Ivanov 的解决方案的固定控制器(此控制器+ N.Ivanov 的 ajax = 解决方案)

public ActionResult SendFridgeItems(fridge[] items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items.ToString());
        foreach (fridge item in items)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }

【问题讨论】:

  • 把它变成这样,让我知道data: {"items":JSON.stringify($scope.items.data)},

标签: javascript jquery ajax asp.net-mvc


【解决方案1】:

ajax 中的data 字段接受一个对象,你给它一个字符串。假设$scope.items.data 是一个对象,请尝试仅提供您的对象。如果你提供更多关于$scope变量是什么的信息,那么我可以给你一个更好的答案。

代码:

$.ajax({ url: "/Data/sendFridgeItems", type: "POST", d̶a̶t̶a̶:̶ ̶$̶s̶c̶o̶p̶e̶.̶i̶t̶e̶m̶s̶.̶d̶a̶t̶a̶,̶ dataType: "json", contentType: "application/json; charset=utf-8", success: function () { console.log("good!"); }, error: function () { console.log("error"); } });

希望这会有所帮助!


编辑:

在您提供$scope.items.data 的内容后进一步检查,我注意到$scope.items.data 是一个对象数组。因此,为了让 ajax 工作并实际提供有效的 JSON,请尝试以下代码: $.ajax({ url: "/Data/sendFridgeItems", type: "POST", data: { "items": $scope.items.data }, dataType: "json", contentType: "application/json; charset=utf-8", success: function () { console.log("good!"); }, error: function () { console.log("error"); } });

我通过JSONLint 验证了{ "item": $scope.items.data } 是一个有效的JSON

希望这能解决您的问题!

【讨论】:

  • 你也可以这样尝试:data: { item: JSON.stringify($scope.items.data)},希望这会有所帮助!
  • "data: $scope.items.data" 触发“无效的 JSON 原语:Item1”。并且 data: { item: JSON.stringify($scope.items.data)} 触发“无效的 JSON 原语:item”。引用类似 data: { "item": JSON.stringify($scope.items.data) } 会引发相同的错误。变量与函数在同一范围内。以 JSON 格式将我的 $scope.items.data 数据添加到问题
  • @Ryu 我已经更新了我的答案,检查EDIT,希望它成功!
  • 感谢您的帮助。对不起,我忘了提到 $scope.items.data 是一个数组。我更新了问题,添加了 $scope.items 值。我也检查了 JSON,它是正确的,但即使使用您的新解决方案,我也会发现 xhr.responseText 出错,并且响应文本显示“无效的 JSON 原语:项目”。
  • 最后我修好了,问题出在控制器上。我使用了数据:{items: $scope.desserts.data},但控制器也需要修复,而不是我使用“fridge[] items”的字符串,冰箱是 ac# 类,具有与 JS 数组相同的字段,并且我删除了行冰箱[]冰箱项目= JsonConvert.DeserializeObject(项目.ToString()),因为现在我不需要反序列化数组。
【解决方案2】:

尝试 JSON Parse 将数据解析为 Object 并将其发送到控制器

$.ajax({
    url: "/Data/sendFridgeItems",
    type: "POST",
    data: JSON.parse($scope.items.data),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function () {
        console.log("good!");
    },
    error: function () {
        console.log("error");
    }
});

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多