Search code examples
c#asp.net-core-mvctelerik-grid.net-5remote-validation

get "Request Payload" in asp.net core controller


on the client side, I do

$.ajax({
    url: '/emplacements/keyexist',
    type: "POST",
    data: JSON.stringify(postData),
    dataType: "json",
    traditional: true,
    contentType: "application/json; charset=utf-8",

However the values in the action method are always 'null'

[AcceptVerbs("GET", "POST")]
public IActionResult KeyExist(
    string nom,            //[Bind(Prefix = nameof(EmplacementDTO.Nom))],
    int id                 //[Bind(Prefix = nameof(EmplacementDTO.Id))]
)
{
    // nom == null
    // id == 0

enter image description here how to fix it?


Solution

  • first make a model for your payload like below.

    public class MyPayload
    {
        public string Nom{ get; set; }
    
        public int Id { get; set; }
    }
    

    and inside your controller Action method

    public IActionResult KeyExist([FromBody] MyPayload payload)
    

    [FromBody] will automatically map the request body if property names are matched.

    and your ajax call has another issue that you sending the Id as string but the Controller expect an int