Contador6 Contador6 - 1 month ago 8
Javascript Question

Send jsonArray to method MVC controller

I have the following ajax script

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


This script is responsible for executing method in controller with List as parameter

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


Model Participant looks like this

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; }
}


When I click button to execute ajax script it redirects me to controller method and in debbuger I see that parameter IList participants is null? What could be the reason?

Answer Source

You have an error in your jQuery, you need to set the contentType, not the dataType property:

$.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);
    }
});