代码之家  ›  专栏  ›  技术社区  ›  Pablo

为什么POST-request方法返回null,但GET-request返回正确的对象

  •  0
  • Pablo  · 技术社区  · 2 年前

    这是我的控制器代码:

    [HttpPost]
    public async Task<JsonResult> GetWebsite(int Id)
    {
        var website = await _uWebsitesService.GetWebsite(Id);
        return (website == null ? this.Json("Website Not Found") : this.Json(website));
    }
    

    $(".edit-website-btn").on("click", function () {
    
    let id = $(this).attr('data-id');
    
    $.ajax({
        type: "POST",
        url: "/userpanel/GetWebsite/",
        data: { Id: id },
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            console.log(result);
        },
        error: function (error) {
            console.log(error);
        },
      })
    })
    

    2 回复  |  直到 2 年前
        1
  •  1
  •   Serge    2 年前

    这是因为对于post方法,您使用的应用程序/json内容不会向操作发送id,因此操作在默认情况下使用id=0,并且无法获取任何数据。Get操作具有正确的id并返回数据。您可以通过删除contentType:“application/json”来尝试修复post的ajax

    $.ajax({
        type: "POST",
        url: "/userpanel/GetWebsite/",
        data: { Id: id },
        dataType: "json",
        .....
    

    但是我觉得用GET更好

    $.ajax({
        type: "GET",
        url: "/userpanel/GetWebsite?id="+id,
       dataType: "json",
        ...
    

     let Id = $(this).data('id');
     //or
     let Id = this.getAttribute('data-id');
    
        2
  •  1
  •   gunr2171    2 年前

    你的 data ajax调用中的参数是一个对象,恰好有一个名为 Id 具有您想要的价值。

    只是 整数,而不是对象 称为“Id”。

    data: id,
    

    为了帮助实现C的绑定,还应该指定参数来自请求体。这在技术上是可选的,但可能有助于提高可维护性,并确保您的值不会意外地从另一个来源(如rouge查询参数)传入。

    public async Task<JsonResult> GetWebsite([FromBody] int Id)