在MVC的架構底下,將自訂的List<Object> 透過AJAX 傳到Controller
首先定義ViewModel
//自訂的物件
public class PRS0011OrderModel
{
public int SEQ { get; set; }
public String APID { get; set; }
}
//List<Object>
public class PRS0011ViewModel
{
public List<PRS0011OrderModel> Orders { get; set; }
}
JS:
function SavePRS0011() {
var _array = [];
//將自訂的物件塞入Array中
$.each($("#tbAPSORT").find('tr'), function (index, ele) {
if ($(ele).data('apid') != undefined) {
_array.push({ SEQ: index, APID: $(ele).data('apid') });
}
});
if (_array.length > 0) {
//剛剛定義的ViewModel裡面物件名稱是Orders
var _Object = { Orders: _array };
$.ajax({
type: "POST",
url: 'URL',
data: JSON.stringify(_Object),
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (_result) {
},
error: function (error) {
alert('error; ' + error);
}
});
}
}
最後Controller在接參數的時候直接用訂好的ViewModel就好,很方便
[HttpPost]
public ActionResult Action(PRS0011ViewModel model)
{
ResultObject _resultObject = new ResultObject();
return Json(_resultObject);
}
這樣就可以把自訂的List<Object>傳到後端,
PS,POST到後端的資料長度是有限制的,如果要擴充可在Web.Config
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
以上