如何在 Ajax Post 的 .net core mvc 中使用模型绑定器?

How to use model binder in .net core mvc with Ajax Post?

我是 .net 核心 MVC 的新手,正在尝试执行类似于 .net 框架 MVC 的 Ajax post。我只是想 POST 一个单一的 int 值到下面的控制器操作。 Ajax 调用命中控制器,但操作参数始终为 0。我验证了 Ajax 请求负载中发送的整数值是否正确。我错过了什么?

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Ajax_GenerateSecretNum([FromBody]int lower)
    {

        return Json(new { success = true });
    }

  $.ajax({
            url: '@Url.Action("Ajax_GenerateSecretNum", "Home")',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: { lower: lower },
            success: function (response) {

            }
        });

您可以为控制器参数创建一个模型 (DTO),并在将数据发布到控制器之前对您的数据使用 JSON.stringify()

 $.ajax({
    url: '@Url.Action("Ajax_GenerateSecretNum", "Home")',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: JSON.stringify({ lower: lower }),
    success: function (response) {

    }
});

public class ModelDto
{
    public int Lower { get; set; }
}

[HttpPost]
public IActionResult Ajax_GenerateSecretNum([FromBody]ModelDto model)
{
    // model.Lower should contain your int
    return Json(new { success = true });
}
            $.ajax({
                url: '@Url.Action("Ajax_GenerateSecretNum", "Home")',
                type: 'POST',               
                data: { "lower": lower, "upper": upper },
                success: function (response) {

                }   
            });

将我的 jQuery ajax 更改为上述示例解决了问题。我不确定为什么,但看起来指定额外的 ajax 参数会导致值无法模型绑定。更改 ajax 后,我还能够从控制器操作中删除 [FromBody] 属性。

您可以执行如下操作:

    $.ajax({
        method: "POST",
        data: { "Property1": "value1", "Property2": "value2"},
        url: "@Url.Action("Ajax_GenerateSecretNum", "Home")",
        success: function (data) {
            //success login
        },
        error: function (data) {
            alert('error' + data.status);
        }
    });

控制器如下所示:

[HttpPost]
public ActionResult Ajax_GenerateSecretNum(ModelClass modelClass)
{
    //You logic will be here
}