【问题标题】:Passing item Id in the loop to Jquery将循环中的项目 ID 传递给 Jquery
【发布时间】:2019-06-18 09:35:20
【问题描述】:

我正在为每个评论构建一个“喜欢”按钮,并使用 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);
  }

【问题讨论】:

  • 您是否只想将一个 id 传递给控制器​​?

标签: jquery asp.net-mvc razor asp.net-core .net-core


【解决方案1】:

您目前遇到的问题是您的 jQuery 代码仅被分配给来自 Model.PostComments 循环的一个 id - 大概是最后一个。您在引用 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。

【讨论】:

  • 感谢您的出色回答,但现在无法点击 标签。
  • a 标签必须有一个href 才能被点击。如果您不希望它真正去任何地方,只需使用href="#"
  • @ChrisPratt 非常好。我更新了答案。我还在点击事件中添加了对 preventDefault() 的调用,以阻止将 # 添加到 URL
  • 此外,实体上的Id 属性不应直接用作元素上的id 属性。此属性通常为 int,并且 HTML id 不能以数字开头。相反,您需要执行id="item@(item.Id)" 之类的操作。一般来说,这种东西最好使用data-*属性,即data-id="@item.Id"
  • 检查控制台是否有错误,同时观察网络流量以查看是否发送了请求以及响应是什么。您没有处理任何错误,因此可能是服务器端代码返回 500。
猜你喜欢
  • 2014-02-05
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多