<script type="text/javascript">
$(function () {
$(".gridViewRow, .gridViewAltRow").hover(
function () {
$(this).closest("table").find("tr.gridViewSubCategories").hide();
var self = this;
var subCategoriesGridRow = $(this).next("tr.gridViewSubCategories");
if (subCategoriesGridRow.length == 0) {
var categoryId = parseInt($(this).find("[data-categoryId]").attr("data-categoryId"));
$.ajax({
url: '<%= ResolveClientUrl("~/WebForm2.aspx/GetSubCategories") %>',
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
data : "{ 'categoryId' : " + categoryId + " }",
success: function (data) {
var subTable = $("<table class='subCategories'><tr><th>Id</th><th>Name</th></tr></table>");
data = data.d;
if (data.length) {
for (var i = 1; i < data.length; ++i) {
var tr = $("<tr ><td>" + data[i].id + "</td><td>" + data[i].name + "</td></tr>");
$(subTable).append(tr);
}
}
var gridRow = $("<tr class='gridViewSubCategories'></tr>");
var subCatCell = $("<td colspan='2' ></td>");
subTable.appendTo(subCatCell);
subCatCell.appendTo(gridRow);
$(self).after(gridRow);
},
error: function (aaa, bbb, ccc) {
}
});
}
else {
subCategoriesGridRow.show();
}
},
function () {
$(this).closest("table").find("tr.gridViewSubCategories").hide();
});
});
</script>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" RowStyle-CssClass="gridViewRow"
AlternatingRowStyle-CssClass="gridViewAltRow" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<span data-categoryId='<%# Eval("Id") %>'>
<%# Eval("Id") %>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
代码隐藏
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = Enumerable.Range(1, 10)
.Select(id => new {Id = id, Name = Guid.NewGuid().ToString()});
GridView1.DataBind();
}
}
[WebMethod]
public static object GetSubCategories(int categoryId)
{
return Enumerable.Range(categoryId, 10)
.Select(id => new {id = id, name = id.ToString()})
.ToList();
}
最好使用一些 jsRender 之类的 javascript 模板引擎。