在ASP.NET GridView中实现JQuery Datatable

3

我希望能够在ASP.NET GridView中使用"JQuery Datatable"。

我尝试了一些方法,但并没有成功。

GridView -

<asp:GridView ID="gridViewTasks" runat="server" AutoGenerateColumns="false" CssClass="table table-striped table-bordered dt-responsive nowrap" Width="100%">
    <Columns>
        <asp:BoundField DataField="task_id" HeaderText="TaskID" Visible="false" />
        <asp:BoundField DataField="task_description" HeaderText="Task Name" />
        <asp:BoundField DataField="task_detail" HeaderText="Task Detail" Visible="false" />
        <asp:BoundField DataField="task_createdate" HeaderText="Create Date" />
        <asp:BoundField DataField="task_targetdate" HeaderText="Target Date" />
        <asp:BoundField DataField="task_isReaded" HeaderText="Task Read" Visible="false" />
        <asp:BoundField DataField="product_id" HeaderText="ProductID" Visible="false" />
        <asp:BoundField DataField="product_name" HeaderText="Product" />
        <asp:BoundField DataField="status_id" HeaderText="StatusID" Visible="false" />
        <asp:BoundField DataField="status_name" HeaderText="Status" />
        <asp:BoundField DataField="severity_id" HeaderText="SeverityID" Visible="false" />
        <asp:BoundField DataField="severity_name" HeaderText="Severity" />
        <asp:BoundField DataField="user_masterID" HeaderText="MasterID" Visible="false" />
        <asp:BoundField DataField="gorevi_veren" HeaderText="Master" />
        <asp:BoundField DataField="user_slaveID" HeaderText="SlaveID" Visible="false" />
        <asp:BoundField DataField="görevi_alan" HeaderText="Slave" />
        <asp:BoundField DataField="task_score" HeaderText="Score" />
    </Columns>
</asp:GridView>

JavaScript -

1

$(document).ready( function () {
$('#gridViewTasks').DataTable();} );

2

$(document).ready( function () {
$("#gridViewTasks").prepend( $("<thead></thead>").append( $(this).find("tr:first") ) ).DataTable() ;} );

我使用的脚本和CSS:

<script src="jquery-1.9.1.min.js"></script>
<link href="jquery.dataTables.min.css" rel="stylesheet" />
<script src="jquery.dataTables.min.js"></script>

同时我也尝试了girdView_PreRender函数。

当我使用GridView时,我会添加参考。

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
    gridViewTasks.DataSource = Sample.GetData();
    gridViewTasks.DataBind();

    if (gridViewTasks.Rows.Count > 0)
    {
        //This replaces <td> with <th> and adds the scope attribute
        gridViewTasks.UseAccessibleHeader = true;
        //This will add the <thead> and <tbody> elements
        gridViewTasks.HeaderRow.TableSection = TableRowSection.TableHeader;

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

    }
}

Code Behind - 我正在使用Linq to SQL

var sorgu = from gorev in db.Tasks
join ga in db.Users on gorev.user_slaveID equals ga.user_id
join gv in db.Users on gorev.user_masterID equals gv.user_id
join product in db.Products on gorev.product_id equals product.product_id
join severity in db.Severities on gorev.severity_id equals severity.severity_id
join status in db.Status on gorev.status_id equals status.status_id
select new
{
    gorev.task_id,
    gorev.task_description,
    gorev.task_detail,
    gorev.task_createdate,
    gorev.task_targetdate,
    gorev.task_isReaded,
    product.product_id,
    product.product_name,
    status.status_id,
    status.status_name,
    severity.severity_id,
    severity.severity_name,
    gorev.user_masterID,
    gorevi_veren = gv.user_username,
    gorev.user_slaveID,
    görevi_alan = ga.user_username,
    gorev.task_score                       
};

gridViewTasks.DataSource = sorgu;
gridViewTasks.DataBind();

所以,我怎样在ASP.NET GridView中实现JQuery DataTable呢?
2个回答

14

这几行代码就足以让它工作了。你不需要预渲染事件。只需在Page_Load中绑定IsPostBack检查即可。我确实添加了一个RowDataBound事件到GridView中,通过编程方式而不是使用jQuery添加了<thead><tbody>部分。

<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"></asp:GridView>

<script type="text/javascript">
    $(document).ready(function () {
        $('#<%= GridView1.ClientID %>').DataTable();
    });
</script>

代码后置

protected void Page_Load(object sender, EventArgs e)
{
    //check for a postback
    if (!Page.IsPostBack)
    {
        //bind the gridview data
        GridView1.DataSource = source;
        GridView1.DataBind();
    }
}


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is the header row
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //add the thead and tbody section programatically
        e.Row.TableSection = TableRowSection.TableHeader;
    }
}

更新

如果您在UpdatePanel中使用DataTable,请使用以下JavaScript代码来确保在异步PostBack之后正确绑定。

<script type="text/javascript">

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function () {
        createDataTable();
    });

    createDataTable();

    function createDataTable() {
        $('#<%= GridView1.ClientID %>').DataTable();
    }
</script>

aspnet可以在客户端重命名控件的ID,因此gridViewTasks可以变成PlaceHolder_GridView1。如果发生这种情况,则$("#gridViewTasks")将无法工作,因为该ID不存在。使用ClientID将确保您在客户端使用正确的ID。 - VDWWD
在这种情况下,RowDataBound事件旨在向GridView添加<thead><tbody>,这些默认情况下不存在。它替换了您的$("#gridViewTasks").prepend( $("<thead></thead>").append( $(this).find("tr:first")。但是,如果您希望使用jQuery方法添加它们,则可以将其删除。 - VDWWD
好的。非常感谢。最后,你知道我如何在Jquery DataTable中添加Excell、Print等按钮吗?如果你知道,能和我分享一下吗? - Mevlüt Soner
我可以再问一件事吗?我在GridView中添加了以模态弹出窗口打开的编辑按钮。当我点击编辑按钮时,模态弹出窗口会打开,而jQuery表格模块会消失。在页面刷新后模块会重新出现。我该如何解决这个问题?也就是说,当我点击编辑按钮时,jQuery表格模块不会消失。 - Mevlüt Soner
如果数据表格消失了,您必须再次调用 $('#<%= GridView1.ClientID %>').DataTable();。如果使用 UpdatePanel,请使用 PageRequestManager https://stackoverflow.com/a/45442175/5836671 - VDWWD
显示剩余2条评论

1

试试这个,它会按照你的需求工作。

<div class="table-responsive">
    <asp:GridView ID="gvExample" runat="server">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                   <%-- Binding Expression--%>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

调用必要的CSS文件(bootstrap.css、font-awesome.css等)

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" />

调用必要的脚本(bootstrap.js、jquery.js等)

<!-- jQuery CDN - Slim version (=without AJAX) -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>

<!-- Popper.JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>

<!-- Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>

<!-- jQuery Data Tables CDN -->
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js" type="text/javascript" charset="utf8"></script>

<!-- Bootstrap Data Tables JS -->
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js" type="text/javascript" charset="utf8"></script>

然后添加以下脚本

 <script>
    $(document).ready(function () {
        $('#<%= gvExample.ClientID%>').prepend($("<thead></thead>").append($("#<%= gvExample.ClientID%>").find("tr:first"))).DataTable({
            stateSave: true,
        });
    });
</script>

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