javascript - 来自ajax的 Controller 中的空参数

标签 javascript jquery ajax asp.net-mvc

当用户单击保存按钮时,JavaScript 函数使用 AJAX 调用 Controller 并发送有关对象的 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");
        }
    });

Controller

[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 参数发送数据的方式不正确,因为数据足够大。我想知道是否有更好的方法将我的数据发送到 Controller ?

我尝试以这种方式发送,但 Controller 收到空值。

$.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"
      }
    ]
};

Fixed Controller For N.Ivanov's solution (this controller+ N.Ivanov's ajax = solution)

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

最佳答案

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

代码:

$.ajax({ 网址:“/数据/sendFridgeItems”, 输入:“发布”, d̶a̶t̶a̶:̶̶$̶s̶c̶o̶p̶e̶.̶i̶t̶e̶m̶s̶.̶d̶a̶t̶a̶,̶ 数据类型:“json”, contentType: "application/json; charset=utf-8", 成功:函数(){ console.log("好!"); }, 错误:函数(){ console.log("错误"); } });

希望这对您有所帮助!


编辑:

在您提供了 $scope.items.data 的内容后进一步检查让我注意到 $scope.items.data 是一个对象数组。因此,为了让 ajax 工作并实际提供有效的 JSON,请尝试以下代码: $.ajax({ 网址:“/数据/sendFridgeItems”, 输入:“发布”, 数据:{“项目”:$scope.items.data}, 数据类型:“json”, contentType: "application/json; charset=utf-8", 成功:函数(){ console.log("好!"); }, 错误:函数(){ console.log("错误"); } });

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

希望这能解决您的问题!

关于javascript - 来自ajax的 Controller 中的空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44946220/

相关文章:

jquery - AJAX post 不发送数据到 laravel Controller

php - jQuery、ajax、php、mysql : auto-suggest form input

javascript - 仅在 Vue 中填写字段后提交表单

javascript - 这是用ajax处理发布变量的好方法吗

c# - 如何将数据库中的数据插入到Jquery脚本中

javascript - 模态下拉列表

javascript - 使用 JQuery/Ajax 将我的 API 连接到 HTML

javascript - 如何使用元素检查器在网站上运行我自己的事件处理 Javascript 代码?

javascript - JS : setInterval and clearIntervals with jQuery

javascript - ie10支持从剪贴板粘贴图片吗?