首页 > 解决方案 > 将循环中的项目 ID 传递给 Jquery

问题描述

我正在为每个评论构建一个“喜欢”按钮,并使用 jQuery 将数据发布到PostsController. 如何@item.Id为循环中的每个项目传递 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);
  }

标签: jqueryasp.net-mvcrazorasp.net-core.net-core

解决方案


您当前遇到的问题是您的 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 进行硬编码。


推荐阅读