Search code examples
asp.net-corerazor-pages.net-6.0

AJAX Post request with Razor Pages parameter class


I'm trying to implement a simple ajax with razor pages, but the parameter is not transmitted.

Here is the ajax

document.querySelector("#btnEditTeamSave").addEventListener("click", function editTeamSubmit(event) { 
    
    event.preventDefault();
    var theTeam = { Id:$('#btnEditTeamSave').val(), Name: $('#EditTeamName').val(), Description: $('#EditTeamDescription').val(), MachineId: $('#EditTeamMachine').val(),Active: $('#EditTeamActive').val(), Color: $('#EditTeamColorPicker').val()  };
    //JSON.stringify(theTeam)

       console.log(JSON.stringify(theTeam));
       $.ajax({
            type: "POST",
            url: "?handler=Team",
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            data: JSON.stringify(theTeam),
            headers: {
                RequestVerificationToken:
                    $('input:hidden[name="__RequestVerificationToken"]').val()
            },
        })
            .done(function (result) {
                console.log(result);
            });
  },false)  

And here is the model

   public class TeamShort
    {
        public int? Id { get; set; }
        public string? Name { get; set; }
        public string? Description { get; set; }
        public string? MachineId { get; set; }
        public bool? Active { get; set; }
        public string? Color { get; set; }
    }

public IActionResult OnPostTeam([FromBody]TeamShort theTeam)
{


    return new JsonResult("succes"); 
}

But the model theTeam is empty

https://i.sstatic.net/TwFx0.png

This is the log from the console with theTeam

https://i.sstatic.net/ZPpFe.png


Solution

  • Finally solved

    https://i.sstatic.net/uKoyC.png

    The issue was the type of attributes from the class.

    The active attribute has the value "on", and this value cannot be converted into "true"