我有一个带有inputModel参数的MVC控制器动作,它具有列表类型属性,我使用$('form').serialize()
来序列化表单内容并将我的一些自定义数据附加到序列化字符串,但是在action方法输入中模型对象列表属性为空,
任何人都可以帮助我,下面是代码示例
我的控制器
[HttpPost]
public ActionResult Edit(ALDS.Web.Areas.Direct2M3.Models.ItemInputModel collection)
{ }
ItemInputModel类
public class ItemInputModel
{
//......Some property here..
public List<FabricCompositionInputModel> FabricCompositions { get; set; }
}
FabricCompositionInputModel类
public class FabricCompositionInputModel
{
public int ItemID { get; set; }
public string CompositionCode { get; set; }
public decimal Value { get; set; }
}
Ajax调用
function save() {
var compositionData = generateCompositionForSave(); //Returns array
var data = $('form').serialize();
var d2 = JSON.stringify(compositionData);
var data2 = data + '&FabricCompositions=' + d2;
$.ajax({
type: 'POST',
dataType: 'json' ,
cache: false,
url: '/ItemMaster/Edit',
data: data2,
success: function (data, textStatus, jqXHR) {
sucess(data);
},
error: function (jqXHR, textStatus, errorThrown) {
failed(jqXHR);
}
});
}
数组生成函数
function generateCompositionForSave() {
var arr = [];
var delClassList = $('#compositionContainer').find('.btnRemoveCompositions');
for (var c = 0; c < delClassList.length; c++) {
var row = $(delClassList[c]).closest('.row');
var code = row.find('.compositionCode').val();
var value = parseInt(row.find('.compositionValue').val());
arr.push({ItemID:0, CompositionCode:code, Value:value});
}
return arr;
}
答案 0 :(得分:1)
您没有正确构建数据,而且需要
var compositionData = generateCompositionForSave();
var data = $('form').serializeObject(); // see function below
data['FabricCompositions'] = compositionData; // add the array to the serialized data
var data2 = JSON.stringify({ collection: data }), // stringify it
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8", // add contentType
dataType: 'json' ,
cache: false,
url: '@Url.Action("Edit", "ItemMaster")', // don't hard code your url's
data: data2,
success: function (data, textStatus, jqXHR) {
....
并添加以下功能(警告:这对于<select multiple>
元素无法正常工作)
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] === undefined) {
o[this.name] = this.value || '';
}
});
return o;
};
请注意,如果您使用for
循环正确生成表单控件,或使用自定义EditorTemplate
生成FabricCompositionInputModel
类型(请参阅Post an HTML Table to ADO.NET DataTable),例如
for(int i = 0; i < Model.FabricCompositions.Count; i++)
{
@Html.TextBoxFor(m => m.FabricCompositions[i].CompositionCode)
@Html.TextBoxFor(m => m.FabricCompositions[i].Value)
}
然后所需要的只是
var data = $('form').serialize();
$.ajax({
type: 'POST',
dataType: 'json' ,
cache: false,
url: '@Url.Action("Edit", "ItemMaster")',
data: data,
success: function (data, textStatus, jqXHR) {