2

I am building a 'like' button for each comment and posting data using jQuery to PostsController. How can I pass the Id value, @item.Id, for each item in the loop? Whats the proper way to handle it in jQuery code?

@foreach (var item in Model.PostComments)
{ 
  <a id="@item.Id" class="btn btn-success"><span class="glyphicon glyphicon-thumbs-up"></span></a>
 }
$(document).ready(function() {
  $("#@item.Id").click(function() {
    var FollowOptions = {};
    FollowOptions.url = "/Posts/CommentUp/";
    FollowOptions.data = { id: "@Model.PostComment.Id" };
    $.ajax(FollowOptions);
  });
});
public IActionResult CommentUp(Guid id)
{
  PostComment PostComment = _context.PostComment.Where(m => m.Id == id).SingleOrDefault();
  if (PostComment == null)
  {
    return NotFound();
  }

  string currentuserid = _userManager.GetUserId(User);
  if (_context.CommentMetric.Where(f => f.PostCommentId == id && f.ApplicationUserId == currentuserid).Count() == 0)
  {
    _context.CommentMetric.Add(new CommentMetric
    {
      Id = Guid.NewGuid(),
      ApplicationUserId = currentuserid,
      PostCommentId = id,
      VoteValue = 1
    });

    return RedirectToAction("Details/" + id);
  }
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
mohammed alani
  • 336
  • 4
  • 18

1 Answers1

4

The issue you have currently is that your jQuery code is only being assigned on one id from the Model.PostComments loop - presumably the last one. You have the same issue in referencing Model.PostComment.Id.

It would make more sense to apply a common class to the a elements you create in the loop, then read the id attribute from that and send it in the request, something like this:

@foreach (var item in Model.PostComments)
{ 
  <a id="@item.Id" class="btn btn-success btn-like" href="#"><span class="glyphicon glyphicon-thumbs-up"></span></a>
}
$(document).ready(function() {
  $('a.btn-like').click(function(e) {
    e.preventDefault();
    $.ajax({
      url: '@Url.Action("CommentUp", "Posts")',
      data: { id: this.id }
    });
  });
});

Note the use of Url.Action() instead of hard-coding the URL in the example.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339