你可以把相关行的ID在按钮的data-id
属性和设置seeComments
作为按钮的class
。你不包括你的模型类的定义,因此假定这是一个IEnumerable
,您的视图代码会是这样
@foreach (var answer in Model)
{
.....
<button type="button" data-id="@answer.ID" class="seeComments">See comments</button>
}
或像下面如果你的模型类包含一个名为嵌套IEnumerable
财产Answers
@foreach (var answer in Model.Answers)
{
.....
<button type="button" data-id="@answer.ID" class="seeComments">See comments</button>
}
然后结合的Click事件使用.seeComments
选择所有See Comments
按钮和使用.data("id")
抓住像下面
$(".seeComments").click(function() {
// this will display the data-id value of the clicked button
alert($(this).data("id"));
});
的ID
尼斯,工作。但不得不将@Model [i]更改为@ Model.ElementAt(i),因为无法在IEnumerable上使用索引。并感谢您额外的脚本信息。必须查看“最接近的”,但现在明白了。作品美丽... ;-) – nanonerd 2014-09-27 05:47:39
然后你不需要一个'for'循环(就像你在你的问题中指出的那样)。如果它的'IEnumerable',你可以使用'foreach'循环例如'foreach(模型中的var item){...'并使用'@ item.Name' – 2014-09-27 06:08:42
最初,我使用的是foreach。但是,我需要计数,因为我想显示高亮部分中的前5个项目,然后显示另一个部分中的剩余部分。有没有办法使用foreach进行计数?这就是为什么我切换到For循环。再次感谢,一点一点的学习...... – nanonerd 2014-09-27 14:27:23