我在jQuery中有一个对象数组:
function customersList() {
this.selectedCustomers = [];
}
function customerObject(customerId, bookingId) {
this.customerId = customerId;
this.bookingId = bookingId;
}
我需要将其发布到我的控制器:
[HttpPost]
public ActionResult CreateMultipleCasesFormPost(CreateMultipleCasesModel model)
{
return PartialView("_CreateMultipleCases", model);
}
我的ViewModel:
public class CreateMultipleCasesModel
{
[Display(Name = "Selected Customers")]
public List<CustomerList> Customers { get; set; }
我需要将jQuery中的数组和此表单中的数据传递给我的控制器(我的视图模型包含其他属性):
$('#createMultipleCasesForm')
这是我的Post Form jQuery Code:
$('#createMultipleCasesBtn').click(function () {
var btn = $(this);
var mUrl = btn.data('actionurl');
var formModel = $('#createMultipleCasesForm').serializeArray();
var customerList = customersList.selectedCustomers();
var requestData = {
model: formModel,
Customers: customerList
};
var sData = JSON.stringify(requestData);
$.ajax({
url: mUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: sData,
success: function (response) {
debugger;
},
error: function (response) {
$('#ErrorMessage').html('<span class="icon black cross"></span>' + response.Message);
}
});
});
我的jQuery模型不是绑定客户对象数组或表单,我在这里做错了什么?
修改
发布Back my Form时会发生什么:
答案 0 :(得分:3)
我找到了一个解决方案,这对我有用:
$('#createMultipleCasesBtn').click(function () {
var btn = $(this);
var mUrl = btn.data('actionurl');
var formModel = $('#createMultipleCasesForm').serializeObject();
formModel['Customers'] = customersList.selectedCustomers;
var sData = JSON.stringify(formModel);
$.ajax({
url: mUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: sData,
success: function (response) {
},
error: function (response) {
$('#ErrorMessage').html('<span class="icon black cross"></span>' + response.Message);
}
});
});
以下使用此功能:Convert form data to JavaScript object with jQuery
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};