【发布时间】: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