简体   繁体   中英

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

在此处输入图像描述 how to fix it?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM