在 ASP.NET MVC 開發中,當使用 jQuery Ajax 向伺服器傳送複雜資料結構(如巢狀物件、陣列或 List 集合)時,開發者常遇到伺服器端無法正確綁定參數的問題。網路上雖有許多解決方案,但多半著眼於伺服器端反序列化 JSON 字串。本文提出一種在客戶端預先轉換資料格式的做法,讓 MVC 模型綁定器能直接識別並正確對應參數。
jQuery 在提交陣列資料時,會自動在參數名稱後附加 [](例如 items[]),而 MVC 預設模型綁定器期望的格式為 items[0]、items[1] 等索引式命名。此外,巢狀物件需要以點號分隔層級(如 user.name),巢狀陣列則結合兩者(如 users[0].name)。只要在客戶端將 JSON 物件轉換為這種「扁平化鍵值對」格式,伺服器端即可無縫綁定。
以下是一個獨立運作的 JavaScript 閉包函式,專門處理 JSON 到 MVC 參數格式的轉換:
var mvcParamMatch = (function () {
var MvcParameterAdaptive = {};
// 判斷是否為陣列
MvcParameterAdaptive.isArray = Function.isArray || function (o) {
return typeof o === "object" && Object.prototype.toString.call(o) === "[object Array]";
};
// 將陣列轉換為物件(扁平化)
MvcParameterAdaptive.convertArrayToObject = function (arrName, array, saveObj) {
var obj = saveObj || {};
function func(name, arr) {
for (var i in arr) {
if (!MvcParameterAdaptive.isArray(arr[i]) && typeof arr[i] === "object") {
for (var j in arr[i]) {
if (MvcParameterAdaptive.isArray(arr[i][j])) {
func(name + "[" + i + "]." + j, arr[i][j]);
} else if (typeof arr[i][j] === "object") {
MvcParameterAdaptive.convertObject(name + "[" + i + "]." + j + ".", arr[i][j], obj);
} else {
obj[name + "[" + i + "]." + j] = arr[i][j];
}
}
} else {
obj[name + "[" + i + "]"] = arr[i];
}
}
}
func(arrName, array);
return obj;
};
// 將物件轉換為扁平化鍵值對
MvcParameterAdaptive.convertObject = function (objName, turnObj, saveObj) {
var obj = saveObj || {};
function func(name, tobj) {
for (var i in tobj) {
if (MvcParameterAdaptive.isArray(tobj[i])) {
MvcParameterAdaptive.convertArrayToObject(i, tobj[i], obj);
} else if (typeof tobj[i] === "object") {
func(name + i + ".", tobj[i]);
} else {
obj[name + i] = tobj[i];
}
}
}
func(objName, turnObj);
return obj;
};
// 公開介面
return function (json, arrName) {
arrName = arrName || "";
if (typeof json !== "object") throw new Error("請傳入 JSON 物件");
if (MvcParameterAdaptive.isArray(json) && !arrName) throw new Error("請指定陣列名稱,對應 Action 中的參數名稱!");
if (MvcParameterAdaptive.isArray(json)) {
return MvcParameterAdaptive.convertArrayToObject(arrName, json);
}
return MvcParameterAdaptive.convertObject("", json);
};
})();
var sendData = {
"Comment": "qqq",
"Ajax1": { "Name": "sq", "Age": 55, "Ajax3S": { "Ajax3Num": 234 } },
"Ajax2S": [
{ "Note": "aaa", "Num": 12, "Ajax1S": [
{ "Name": "sq1", "Age": 22, "Ajax3S": { "Ajax3Num": 456 } },
{ "Name": "sq2", "Age": 33, "Ajax3S": { "Ajax3Num": 789 } }
]},
{ "Note": "bbb", "Num": 34, "Ajax1S": [
{ "Name": "sq3", "Age": 44, "Ajax3S": { "Ajax3Num": 654 } },
{ "Name": "sq4", "Age": 987 }
]}
]
};
$.ajax({
url: "@Url.Action(\"AjaxTest\")",
data: mvcParamMatch(sendData), // 若根節點為陣列,需傳第二參數:mvcParamMatch(sendData, "參數名")
dataType: "json",
type: "post",
success: function (result) {
alert(result.Message);
},
error: function (a, b, c) { }
});
public class AjaxParamModels
{
public string Comment { get; set; }
public Ajax1 Ajax1 { get; set; }
public List<Ajax2> Ajax2S { get; set; }
}
public class Ajax1
{
public string Name { get; set; }
public int Age { get; set; }
public Ajax3 Ajax3S { get; set; }
}
public class Ajax2
{
public string Note { get; set; }
public int Num { get; set; }
public List<Ajax1> Ajax1S { get; set; }
}
public class Ajax3
{
public int Ajax3Num { get; set; }
}
public class TestController : Controller
{
public ActionResult Index() { return View(); }
public ActionResult AjaxTest(AjaxParamModels model)
{
// 此處可直接存取 model 所有巢狀屬性與集合
return Json(new { Message = "綁定成功!" });
}
}
[FromForm])。採用此方案,前端只需一行 mvcParamMatch(data),即可讓後端輕鬆接收最複雜的資料結構,大幅簡化開發流程。