serge
serge

Reputation: 15229

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?

Upvotes: 2

Views: 7990

Answers (1)

Sabir Hossain
Sabir Hossain

Reputation: 1205

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

Upvotes: 5

Related Questions