【问题标题】:How to use model binder in .net core mvc with Ajax Post?如何在带有 Ajax Post 的 .net core mvc 中使用模型绑定器?
【发布时间】:2019-01-13 19:35:23
【问题描述】:

我是 .net 核心 MVC 的新手,我正在尝试执行类似于 .net 框架 MVC 的 Ajax 帖子。我只是想将一个 int 值发布到下面的控制器操作。 Ajax 调用命中控制器,但 action 参数始终为 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) {

            }
        });

【问题讨论】:

    标签: c# asp.net-core-mvc asp.net-core-2.1


    【解决方案1】:

    您可以为控制器参数创建一个模型 (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 });
    }
    

    【讨论】:

      【解决方案2】:
                  $.ajax({
                      url: '@Url.Action("Ajax_GenerateSecretNum", "Home")',
                      type: 'POST',               
                      data: { "lower": lower, "upper": upper },
                      success: function (response) {
      
                      }   
                  });
      

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

      【讨论】:

        【解决方案3】:

        您可以执行以下操作:

            $.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
        }
        

        【讨论】:

          猜你喜欢
          • 2020-05-26
          • 2021-12-06
          • 1970-01-01
          • 1970-01-01
          • 2020-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多