将Jquery DataTables插件应用于ASP GridView

13

我以前在 PHP 中使用过这个插件,所以我想在 ASP 项目中再次使用它。

但不知何故,它无法与我的 GridView 控件一起使用。

javascript 代码块:

<link type="text/css" href="../scripts/demo_table.css" rel="stylesheet" />  

    <script type="text/javascript" language="javascript" src="../scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" language="javascript" src="../scripts/jquery.dataTables.js"></script>

    <script type="text/javascript" charset="utf-8">
        $(document).ready(function () {
            $(".gvv").dataTable();
        });
        </script>

GridView 代码:

<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="Prop_No" DataSourceID="testtt" CssClass="gvv">

我是否做错了什么,或者DataTables不能用于ASP控件?


1
感谢您提出这个问题。 - strider
3个回答

39

问题在于GridView控件没有添加<thead>元素,而只是将标题行放入生成的表格的<body>部分中,而数据表插件则要求表格中有一个<thead>部分。尝试使用以下脚本:

$(function () {
    $(".gvv").prepend( $("<thead></thead>").append( $(this).find("tr:first") ) ).dataTable();
});

另外,您还可以使用那些不使用默认布局进行呈现的控件,例如 Repeater 或 ListView。


它运行了!我不认为我完全理解它是如何工作的,但它确实可以。你有一些厉害的技能,伙计。谢谢! - strider
感谢您提供这个精彩的答案和解释。这真是帮了我大忙。 - PeonProgrammer
4
不要在 $("#Grid").prepend($("<thead></thead>").append($(this).find("tr:first"))).dataTable(); 中使用 "this",因为如果标记中已经存在另一个表,则会出现问题。相反,请使用 $(#Grid)。因此,请像这样使用:$("#Grid").prepend($("<thead></thead>").append($("#Grid").find("tr:first"))).dataTable(); - Gk_999

17
您可以在GridView的Prerender事件中添加theadtbodytfoot标记,尝试使用以下代码。
protected void GridView1_PreRender(object sender, EventArgs e) {
  // You only need the following 2 lines of code if you are not 
  // using an ObjectDataSource of SqlDataSource
  GridView1.DataSource = Sample.GetData();
  GridView1.DataBind();

  if (GridView1.Rows.Count > 0) {
   //This replaces <td> with <th> and adds the scope attribute
   GridView1.UseAccessibleHeader = true;

   //This will add the <thead> and <tbody> elements
   GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

   //This adds the <tfoot> element. 
   //Remove if you don't have a footer row
   GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
  }

}

请不要忘记在源页面上添加以下事件处理程序。
<asp:GridView ID="GridView1" runat="server" CssClass="gvv"
      OnPreRender="GridView1_PreRender">
</asp:GridView>

现在,您可以像往常一样调用JQuery函数来呈现它。
$(document).ready(function () {
    $(".gvv").dataTable();
});

你使用 .gvv 而不是 .GridView1 吗? - JoshYates1980
@JoshYates1980:只是忘记定义类名了。我已经更新了代码。 - Sunil Acharya

1
请尝试下方的代码。

enter image description here

enter image description here


2
不要在$("#Grid").prepend($("<thead></thead>").append($(this).find("tr:first"))).dataTable();中使用"this",因为如果在"Grid"之前的标记中已经有另一个表格存在,它会产生问题。 相反,请使用$(#Grid)。因此请像这样使用$("#Grid").prepend($("<thead></thead>").append($("#Grid").find("tr:first"))).dataTable(); - Gk_999
感谢您提供的良好提示。 - Mark
感谢您提供的绝佳提示。 - A.M. Patel
除了表格行的条纹和一些杂项之外,所有工作都正常。 “奇数”和“偶数”样式完全被忽略,也没有错误。 - MC9000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接