在 asp.net core 控制器中获取“请求有效负载”

Ser*_*rge 2 c# telerik-grid remote-validation asp.net-core-mvc .net-5

在客户端,我做

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

但是操作方法中的值始终为“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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 如何修复它?

Sab*_*ain 5

首先为您的有效负载制作一个模型,如下所示。

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

    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并在你的控制器Action方法内部

public IActionResult KeyExist([FromBody] MyPayload payload)
Run Code Online (Sandbox Code Playgroud)

[FromBody]如果属性名称匹配,将自动映射请求正文。

并且您的ajax呼叫还有另一个问题,您发送了IdasstringController期望int