【问题标题】:AJAX not passing Handsontable Data to ControllerAJAX 未将 Handsontable 数据传递给控制器
【发布时间】:2015-09-08 03:11:25
【问题描述】:

我正在尝试使用 AJAX 和 jQuery 在我的视图和控制器之间传递数据。

//Creates Container for Default Table
var container = document.getElementById('example');
var userInput = new Handsontable(container, {
    minCols: 10,
    minRows: 5,
    minSpareRows: 1,
    rowHeaders: true,
    colHeaders: [//Column Headers],
    contextMenu: true
});

//Load the Button with the AJAX Command
$(document).ready(function () {
    $("#send").click(function () {

        $.ajax({
            url: '@Url.Action("ProcessRequest","ControllerName")',
            data: JSON.stringify({
                Label1: userInput.getDataAtCol(1),
                Label2: userInput.getDataAtCol(2),
                Label3: userInput.getDataAtCol(3),

            }),
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            type: 'POST',
            success: function (result) {
                alert("Succes");
            },
            error: function (result) {
                alert("Failure");
            }
        });
    });
});

, 但是,当我检查我的服务器端代码(在 C# 中)时,它说我的标签变量的值为 null。

[HttpPost]
    public JsonResult ProcessRequest(
        string Label1,
        string Label2,
        string Label3)
   {
        var _Label1 = Label1;
        var _Label2 = Label2;
        var _Label3 = Label3;

        string message = string.Format("Successful.");
        return Json(new { Success = true, Message = message });
    }

}

该错误是否与 AJAX 命令中的“数据”格式有关,还是我在某处出现类型错误?任何帮助将不胜感激!

【问题讨论】:

  • 我认为您不需要使用JSON.stringify(),只需将JSON对象本身作为数据传递即可。
  • @David 我尝试删除 'JSON.stringify',但没有它,AJAX 命令将无法成功执行。
  • 它是如何失败的?当你发出 HTTP 请求时,发送的数据是什么?
  • 我试图发送的数据来自每个 getDataAtCol() 语句。使用 .stringify() ,AJAX 执行成功,但服务器端变量为空。如果没有 .stringify(),则会执行命令的错误条件(显示“失败”的警报)。
  • 保留 JSON.stringify,你确定 null 的原因不是 userInput.getDataAtCol(1) 返回的东西吗?当您 console.log 该值时,您会得到什么?

标签: c# jquery ajax asp.net-mvc handsontable


【解决方案1】:

结果我需要创建一个包含我的数据的单独变量并将其字符串化两次:一次作为独立调用,再次在 ajax 中作为 JSON.stringify'{data: varaibleName}。出于某种原因,getDataAtCol() 方法确实返回了数据,但结果必须先进行一次字符串化,然后才能在 AJAX 中进行字符串化。感谢 @David 和 @ZekeDroid 的帮助,非常感谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2019-07-16
    相关资源
    最近更新 更多