gpt4 book ai didi

javascript - 将 jsonArray 发送到方法 MVC Controller

转载 作者:行者123 更新时间:2023-11-28 17:49:39 25 4
gpt4 key购买 nike

我有以下ajax脚本

$(function () {
$("#btnConfirmParticipants").click(function () {
var jsonArray = [];
$(".form-horizontal").each(function () {
jsonArray.push({ Name: ($(this).find("#Name").val()), Surname: ($(this).find("#Surname").val()), BirthDate: ($(this).find("#BirthDate").val()) });
});
$.ajax({
type: "POST",
url: "/ClientReservations/AddParticipants",
data: JSON.stringify(jsonArray),
dataType: 'application/json; charset=utf-8',
success: function (response) {

},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});

该脚本负责执行 Controller 中以 List 作为参数的方法

[HttpPost]
[Authorize(Roles ="Klient")]
public ActionResult AddParticipants(IList<Participant> participants)
{
return View();
}

模型参与者看起来像这样

public class Participant
{

public Participant()
{
this.Reservation_House_Participant = new HashSet<Reservation_House_Participant>();
}

[Display(Name ="Id:")]
[Required]
public int Id { get; set; }

[Display(Name ="Imię:")]
[Required]
[MinLength(3),MaxLength(15)]
public string Name { get; set; }

[Display(Name ="Nazwisko:")]
[Required]
[MinLength(3),MaxLength(15)]
public string Surname { get; set; }

[Display(Name ="Data urodzenia:")]
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString ="{0:dd-MM-yyyy}",ApplyFormatInEditMode =true)]
public DateTime BirthDate { get; set; }
}

当我单击按钮执行 ajax 脚本时,它会将我重定向到 Controller 方法,并且在调试器中我看到参数 IListparticipants 为空?可能是什么原因?

最佳答案

您的 jQuery 中有错误,您需要设置 contentType,而不是 dataType 属性:

$.ajax({
type: "POST",
url: "/ClientReservations/AddParticipants",
data: JSON.stringify(jsonArray),
contentType: 'application/json; charset=utf-8', //<-- this line
success: function (response) {

},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});

关于javascript - 将 jsonArray 发送到方法 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45834930/

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