【问题标题】:Passing data from Ajax to ApiController将数据从 Ajax 传递到 ApiController
【发布时间】:2020-02-15 05:23:20
【问题描述】:

我在 Asp.Net Core 中尝试将 Ajax 调用中的数据传递到 API 控制器函数的参数时遇到问题。

我正在使用 Ajax 调用中的数据字段来传递“id”的值。在 API 控制器中,该值应分配给“id”参数,但绝不是。

// Ajax call
$.ajax({
    url: "/api/apicomment/GetPostComments",
    type: "GET",
    data: { 'id' : 2 },
    dataType: "json",
}).done(function (data) {
    // Some function
}).fail(function (handleError) {
    // Some function
});

API 控制器是一个普通的脚手架 API 控制器,我可以在其中使用 id 参数获取特定的 cmets。但是每次我拨打电话时,我都会得到 0 的值。

// API Controller
[HttpGet("{id}")]
[Route("GetPostComments")]
public async Task<ActionResult<IEnumerable<Comment>>> GetSpecificComment(int id)
{
      var comment = await _context.Comment.Where(c => c.PostId == id).ToListAsync();
      if (comment == null)
      {
         return NotFound();
      }

      return comment;
}

尝试了很多不同的东西,但我无法完全弄清楚。

希望有任何可能有帮助的反馈!

【问题讨论】:

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


    【解决方案1】:

    几乎没有什么可以尝试的

    首先关于你的 API url 应该是这样的

    url: "/api/GetPostComments"
    

    这样会干净很多

    第二个你的数据应该是这样的

    data: { id : 2 }
    

    最后你不能混淆这两个

    [HttpGet("{id}")]
    [Route("GetPostComments")]
    

    应该是这样的

    [Route("api/[controller]")]
    [ApiController]
    public class SomeController : ControllerBase {
    
      [HttpGet("GetPostComments/{id}")]
      public async Task<ActionResult<IEnumerable<Comment>>> GetSpecificComment(int id)
      {
          var comment = await _context.Comment.Where(c => c.PostId == id).ToListAsync();
          if (comment == null)
          {
             return NotFound();
          }
    
          return comment;
     }
    
    }
    

    所以你的网址应该是这样的 api/your-controller/GetPostComments/1

    您可以阅读更多here

    【讨论】:

    • 抱歉,无法正常工作。需要注意的一点是,我不希望在获取帖子的 cmets 时更改 url。我只是想获取数据并在帖子中使用它。
    【解决方案2】:

    您也可以通过查询字符串传递:

    1. 注释掉data 行:

      // Ajax call
      $.ajax({
          url: "/api/apicomment/GetPostComments",
          type: "GET",
          data: { 'id' : 2 },
      
      }).done(function (data) {
          // Some function
      }).fail(function (handleError) {
          // Some function
      });
      
    2. 使用FromQuery获取参数:

      public async Task<ActionResult<IEnumerable<Comment>>> GetSpecificComment([FromQuery]int id)
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      相关资源
      最近更新 更多