jquery - 将循环中的项目 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);
}
解决方案
您当前遇到的问题是您的 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 进行硬编码。
推荐阅读
- c++ - '*' 标记之前的预期初始化程序
- terraform - Terraform NAT 网关强制每次应用新资源
- angular - typescript 2.5 的 @angular/core 兼容版本是什么?
- amazon-web-services - cfn-init 检测到哪些类型的更改?
- ruby-on-rails - Ruby on Rails - 如何列出数据库中的项目
- javascript - 我需要输入元素内的小闪烁光标从右侧而不是从左侧开始
- java - 在 PROD 和 TEST 中的数据库的 JNDI 名称之间切换
- xpath - 获取带有文本的元素并且其父元素没有文本
- go - 有没有办法一次构建多个基于 Go 模块的项目?
- sql - 在使用不同的 JOIN 语句时,是否有使用 UNION / UNION ALL 的替代方法?