我有一些剃刀语法,它动态生成一个html表,并在生成数据时填充数据。我需要对我的MVC ASP.Net控制器进行jQuery ajax调用,以获取一些数据进入这个确切表中的另一个字段。现在我想要做的是迭代这个表的子节点,并在加载后逐个单元格地添加这个字段。
但是这没有成功,表格显示好像它没有任何子节点,即剃刀语法没有在那时执行。
我可以做什么,以便在html表填满数据后执行添加额外字段的脚本?这是我的代码。这是剃刀和html语法。
@if (Model.ToList().Count > 0) {
<table id ="groupTable">
<thead>
<tr>
<th>Group Name</th>
<th>Description</th>
</tr>
</thead>
<tbody id="innerTable">
@foreach (var group in Model) {
// display a link with each GroupName as a list which directs to that group with that id
<tr>
<td> @Html.ActionLink(group.Group.GroupName,"DisplayGroup","Groups", new {id = group.GroupId},null) </td>
<td>
@if(group.Group.Description.Length > 40){
@group.Group.Description.Substring(0, 40)
<span>...</span>
}
else
{
@group.Group.Description.Substring(0, group.Group.Description.Length - 1)
}
</td>
</tr>
}
</tbody>
</table>
}
这是在document.ready上执行的脚本
$(document).ready( function() {
@foreach (var group in Model)
{
<text>
jQuery.ajax({
type: 'POST',
url: '/Groups/GetInvitedFriends',
data: { groupId: '@group.Group.GroupId' },
success: function (friendMembers) {
$.each(friendMembers, function (index, friendName) {
// append friend Members at row with index index at that cell
var tbody = $('#innerTable')[0];
var trow = tbody.childNodes[index];
if (trow.index() === 0) {
trow.append('<td> Members </td>');
} else {
trow.append('<td>' + friendName + '</td>');
}
});
},
traditional: true
});
</text>
}
})
答案 0 :(得分:0)
由于javascript只会在客户端浏览器上执行,因此您可以将组的id存储在javascript数组中,然后在文档加载中循环此数组以添加每个额外的单元格。
这是javascript代码:
<script type="text/javascript">
//List of groups id
var groupIds = [];
$(function() {
//Initializing the array with values
@foreach (var group in Model) {
<text>groupIds .push(@group.Group.GroupId);</text>
}
InsertExtraCells(groupIds.pop()); //Insert for the first groupid in the array
});
function InsertExtraCells(groupId) {
jQuery.ajax({
type: 'POST',
url: '/Groups/GetInvitedFriends',
data: { groupId: '@group.Group.GroupId' },
success: function (friendMembers) {
//Do your work
$.each(friendMembers, function (index, friendName) {
// append friend Members at row with index index at that cell
var tbody = $('#innerTable')[0];
var trow = tbody.childNodes[index];
if (trow.index() === 0) {
trow.append('<td> Members </td>');
} else {
trow.append('<td>' + friendName + '</td>');
}
});
//If ids remaining in the array, loop to the next group id
if (groupIds.length > 0) {
InsertExtraCells(groupIds.pop());
}
else {
//Do whatever when finish
}
},
traditional: true
});
}
</script>