其實問題沒那麼復雜
說干就干
復制代碼 代碼如下:
//用於MVC參數適配JavaScript閉包函數
/*
使用方式如下
$
url: "@Url
data: mvcParamMatch(""
dataType: "json"
type: "post"
success:function(result) {
alert(result
}
});
*/
var mvcParamMatch = (function () {
var MvcParameterAdaptive = {};
//驗證是否為數組
MvcParameterAdaptive
return typeof o === "object" &&
Object
};
//將數組轉換為對象
MvcParameterAdaptive
var obj = saveOjb || {};
function func(name
for (var i in arr) {
if (!MvcParameterAdaptive
for (var j in arr[i]) {
if (MvcParameterAdaptive
func(name + "[" + i + "]
} else if (typeof arr[i][j] === "object") {
MvcParameterAdaptive
} else {
obj[name + "[" + i + "]
}
}
} else {
obj[name + "[" + i + "]"] = arr[i];
}
}
}
func(arrName
return obj;
};
//轉換對象
MvcParameterAdaptive
var obj = saveOjb || {};
function func(name
for (var i in tobj) {
if (MvcParameterAdaptive
MvcParameterAdaptive
} else if (typeof tobj[i] === "object") {
func(name + i + "
} else {
obj[name + i] = tobj[i];
}
}
}
func(objName
return obj;
};
return function (json
arrName = arrName || "";
if (typeof json !== "object") throw new Error("請傳入json對象");
if (MvcParameterAdaptive
if (MvcParameterAdaptive
return MvcParameterAdaptive
}
return MvcParameterAdaptive
};
})();
使用方法非常簡單
首先是客戶端的代碼
復制代碼 代碼如下:
var sendData = {
"Comment": "qqq"
"Ajax
"Ajax
{ "Note": "bbb"
};
$
url: "@Url
/*
在此使用閉包函數轉換json對象
那麼需要指定一個名稱
data:mvcParamMatch(sendData
*/
data: mvcParamMatch(sendData)
dataType: "json"
type: "post"
success:function(result) {
alert(result
}
error:function(a
}
});
然後是服務端對應客戶端json的實體類
復制代碼 代碼如下:
public class AjaxParamModels
{
public string Comment { set; get; }
public Ajax
public List<Ajax
}
public class Ajax
{
public string Name { set; get; }
public int Age { set; get; }
public Ajax
}
public class Ajax
{
public string Note { set; get; }
public int Num { set; get; }
public List<Ajax
}
public class Ajax
{
public int Ajax
}
然後是controller中的action代碼
復制代碼 代碼如下:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
return View();
}
public ActionResult AjaxTest(Models
{
//在此可訪問model
return Json(new {Message = "qqqqq"});
}
}
這樣就OK了
From:http://tw.wingwit.com/Article/program/net/201311/14186.html