我正在为每个评论构建一个“赞”按钮,并使用jQuery将数据发布到PostsController。如何为循环中的每个项目传递Id值@item.Id?在jQuery代码中处理它的正确方法是什么?

@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);
  }

最佳答案

您当前遇到的问题是,您的jQuery代码仅在id循环中的一个Model.PostComments上分配-大概是最后一个。您在引用Model.PostComment.Id时遇到相同的问题。

将一个通用类应用于您在循环中创建的a元素,然后从中读取id属性并在请求中发送它,这样会更有意义:

@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 }
    });
  });
});


请注意,在示例中使用了Url.Action()而不是对URL进行硬编码。

07-24 09:46
查看更多