[英]Post DOM array to controller in ASP.NET MVC5
我在采用HTML DOM數組並將其使用ajax調用傳遞給控制器時遇到問題。
這是帖子的發生方式(單擊按鈕):
function onSaveMapClicked() {
$.ajax({
traditional: true,
type: "POST",
url: "/WaferMapper/SaveMap",
contentType: "application/json",
data: JSON.stringify(map.children),
success: function (data) { },
error: function (response) { alert(response); },
});
}
這是應該處理此帖子的控制器代碼:
[HttpPost]
public ActionResult SaveMap(string mapData)
{
return View();
}
因此,這里尚未真正發生任何事情。 我設置了一個斷點,看是否可以擊中它,但我不能擊中它。
這是如何填充數組的示例:
for (var col = 1; col <= cols + 1; col++) {
for (var row = 1; row <= rows + 1; row++) {
var isPrintElement = row != 1 && col != 1;
var elementColor = isPrintElement ? '#ffffff' : '#000000';
this.children.push({
color: elementColor,
color_cache: elementColor,
content: row == 1 ? col - 1 : col == 1 ? row - 1 : "",
isPrint: isPrintElement,
mask: "n/a",
modifier1: new Modifier(""),
modifier2: new Modifier(""),
modifier3: new Modifier(""),
modifier4: new Modifier(""),
modifier5: new Modifier(""),
modifier6: new Modifier(""),
hasModifier: function () {
return (this.modifier1.value != "" ||
this.modifier2.value != "" ||
this.modifier3.value != "" ||
this.modifier4.value != "" ||
this.modifier5.value != "" ||
this.modifier6.value != "");
},
width: width,
height: height,
top: row * (height + this.PRINT_MARGIN),
left: col * (width + this.PRINT_MARGIN)
});
}
}
我知道其他人有這個問題,但是在這里查看其他相關文章,我仍然無法使它正常工作。
單擊“保存地圖”按鈕時,我不斷收到這些錯誤:
POST http://localhost:xxxxx/WaferMapper/SaveMap 500 (Internal Server Error)
感謝Robert McKee的幫助,
訣竅是在地圖對象上實現toJSON()方法。
這是我的基本實現(還有很多工作要做;我只是將map對象的前兩個屬性打包到JSON對象中,最后所有屬性都必須是JSON結構的一部分):
var WaferMap = function (canvas) {
....
....
}
WaferMap.prototype = {
....
....
toJSON: function () {
var json = "[";
for (var i = 0; i < this.children.length; i++) {
var element = this.children[i];
json += "{" +
"\"color:\"" + element.color + "\"," +
"\"color_cache:\"" + element.color_cache + "\"},";
}
return json.substring(0, json.length - 1) + "];"
}
}
現在,此JSON字符串可以正確地發回到控制器。
這是更新的AJAX調用:
function onSaveMapClicked() {
$.ajax({
type: "POST",
url: "/WaferMapper/SaveMap",
contentType: "application/json",
data: {mapData:JSON.stringify(map)},
success: function (data) { },
error: function (response) {
alert(response);
}
});
}
我不是專家,但我認為這是因為沒有發生模型綁定,並且您的控制器期望使用字符串,而不是json對象。
將對象綁定到模型,然后將其傳遞回控制器。
另外,我認為如果您刪除:
contentType: "application/json; charset=utf-8",
現在它將以字符串形式發布,並應命中您的控制器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.