gpt4 book ai didi

javascript - 将数组和表单数据发布到 Controller - MVC Ajax

转载 作者:行者123 更新时间:2023-11-29 19:31:24 25 4
gpt4 key购买 nike

我在 jQuery 中有一个对象数组:

function customersList() {
this.selectedCustomers = [];
}

function customerObject(customerId, bookingId) {
this.customerId = customerId;
this.bookingId = bookingId;
}

我需要将其发布到我的 Controller :

[HttpPost]
public ActionResult CreateMultipleCasesFormPost(CreateMultipleCasesModel model)
{
return PartialView("_CreateMultipleCases", model);
}

我的 View 模型:

public class CreateMultipleCasesModel
{
[Display(Name = "Selected Customers")]
public List<CustomerList> Customers { get; set; }

我需要将来自 jQuery 的数组和来自此表单的数据传递到我的 Controller (我的 View 模型包含其他属性):

$('#createMultipleCasesForm')

这是我的 Post 表单 jQuery 代码:

$('#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 模型没有绑定(bind)客户对象数组或表单,我在这里做错了什么?

编辑

当我回发我的表单时会发生什么: My Customers Array in Model is NULL, all other Fields in my form are not posting back either

最佳答案

我找到了一个对我有用的解决方案:

$('#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;
};

关于javascript - 将数组和表单数据发布到 Controller - MVC Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27268426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com