Chris
Chris

Reputation: 45

Passing data from Ajax to ApiController

I am having issues in Asp.Net Core with trying to pass data in the Ajax call into the parameter of the API Controller function.

I am using the data field in the Ajax call to pass the value of "id". In the API controller this value should be assigned to the "id" parameter, but never is.

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

The API controller is a normal scaffolded API Controller where I get specific comments with the id parameter. But every time I make a call I get the value 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;
}

Have tried many different things, but I can't quite figure it out.

Would love any feedback that might help!

Upvotes: 1

Views: 1364

Answers (2)

Nan Yu
Nan Yu

Reputation: 27588

You can also pass via query string :

  1. Comment out data line :

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

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

Upvotes: 1

Tony
Tony

Reputation: 20142

Few thing to try

First about your API url it should be like this

url: "/api/GetPostComments"

It would be much cleaner

Second your data should be like this

data: { id : 2 }

Finally you cant mix up between these 2

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

It should be like this

[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;
 }

}

So your url should be something like this api/your-controller/GetPostComments/1

You can read more here

Upvotes: 1

Related Questions