mvc.jquery.datatables如何设置导出到csv / pdf

时间:2013-11-25 18:14:40

标签: c# jquery asp.net-mvc datatables jquery-datatables

我查看了datatables.net文档以及nuget包(mvc.jquery.datatables)上的文档,我似乎无法找到如this example中设置导出按钮组的方法。

我的代码设置就像那个例子,它工作正常。但是当我尝试从datatables.net添加示例时,我收到的错误是“无法重新初始化数据表”。

有没有人有关于包的文档来源以及如何设置导出?或者我是否需要进行手动路线并自行设置导出?

以下是代码:

控制器:

 public DataTablesResult<AdminUserListViewModel> GetUsers(DataTablesParam dataTableParam)
    {
        return DataTablesResult.Create(Ctx.ApplicationUser.Select(user => new AdminUserListViewModel()
        {
            Id = user.UserId,
            LastName = user.Applicant.PersonalInformation.LastName,
            FirstName = user.Applicant.PersonalInformation.FirstName,
            Email = user.Applicant.ContactInformation.Email,
            ProgCode = user.Applicant.AcceptedProgressInformation.ProgramCode,
            RepName = user.Applicant.AcceptedProgressInformation.RepName
        }), dataTableParam,
        uv => new
        {
            //Name = "<b>" + uv.Name + "</b>",
            //Hired = uv.Hired == null ? "&lt;pending&gt;" : uv.Hired.Value.ToShortDateString() + " (" + FriendlyDateHelper.GetPrettyDate(uv.Hired.Value) + ") "
        });
    }

查看:

@using Accepted.Web.Areas.Admin.Controllers
@using Mvc.JQuery.Datatables
@using Mvc.JQuery.Datatables.Serialization
@{
ViewBag.Title = "USERS";
Layout = "~/Views/Shared/_Layout.cshtml";

var vm = Html.DataTableVm("table-id", (HomeController h) => h.GetUsers(null));

vm.JsOptions.Add("fnCreatedRow", new Raw(@"function( nRow, aData, iDataIndex ) {
    $(nRow).attr('data-id', aData[0]);
  }
}"));
vm.FilterOn("Id").NumberRange();
vm.StateSave = true;
}
<div class="page-container">
<div class="page-container-nav">
    <ol class="breadcrumb">
        <li class="active">@ViewBag.Title</li>
    </ol>
    <div class="row">
        <div class="col-sm-4">
            <h1>@ViewBag.Title</h1>
        </div>
    </div>
</div>
<div class="page-container-body container-gradient">
    <div class="row">
        <h2 class="thickThinHeader">
            <small>All</small>
            <br />
            Users
        </h2>
    </div>
    <div class="row">

    </div>
    <div class="row">
        <hr />
        @Html.Partial("DataTable", vm)
    </div>
</div>
</div>

@section scripts{
<link type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" rel="stylesheet" />
<script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript">
    //$(document).ready(function () {
    //    $('#table-id').dataTable({
    //        "sDom": 'T<"clear">lfrtip',
    //        "oTableTools": {
    //            "sSwfPath": "copy_csv_xls_pdf.swf"
    //        }
    //    });
    //});

    $('#table-id').delegate('tbody > tr', 'click', function() {
        var id = this.firstElementChild.innerHTML;
        var url = '@Url.Action("User", "Home", new {area = "Admin", id = "__id__"})';
        window.location.href = url.replace('__id__', id);
    });
</script>
}

修改

更简单的代码:

@model IEnumerable<Accepted.Web.ViewModels.AdminUserListViewModel>
@{
ViewBag.Title = "USERS";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="page-container">
<div class="page-container-body container-gradient">
    <div class="row">
        <table class="display table table-condensed table-hover" id="table-id">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var obj in Model)
                {
                    <tr>
                        <td>
                            @obj.FirstName
                        </td>
                        <td>
                            @obj.LastName
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>
</div>

@section scripts{
<link type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" rel="stylesheet" />
<script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('#table-id').dataTable({
            "bPaginate": true,
            "sPaginationType": "full_numbers",
            "bLengthChange": true,
            "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
            "iDisplayLength": 25,
            "aSorting": [1, 'asc'],
            "oLanguage": {
                "sLengthMenu": "<span class='lenghtMenu'> _MENU_</span><span class='lengthLabel'>Page Size:</span>",
            },
            "sDom": '<"table_top"fl<"clear">>,<"tbl_tools"C<"clear">>,<"table_content"t>,<"table_bottom"iTp<"clear">>',
            "oTableTools": {
                "sSwfPath": "Areas/Admin/media/swf/copy_csv_xls_pdf.swf",
                "aButtons": ["copy", "csv", "pdf", "print"]
            }
        });
    });
    $('#table-id').delegate('tbody > tr', 'click', function () {
        var id = this.firstElementChild.innerHTML;
        var url = '@Url.Action("User", "Home", new { area = "Admin", id = "__id__" })';
        window.location.href = url.replace('__id__', id);
    });
</script>
}

1 个答案:

答案 0 :(得分:2)

这是一个例子,希望它有所帮助。

在您的JS文件中

<script src="~/Scripts/data-table.jquery.js"></script>
<script src="~/Scripts/TableTools.js"></script>
<script src="~/Scripts/ZeroClipboard.js"></script>
$(function () {
    $('#data_tbl').dataTable({
        "sPaginationType": "full_numbers",
        "bLengthChange": true,
        "aLengthMenu": [[25, 50, 100,-1], [25, 50, 100, "All"]],
        "iDisplayLength": 25,
        "aaSorting": [1, 'asc'],
        "oLanguage": {
            "sLengthMenu": "<span class='lenghtMenu'> _MENU_</span><span class='lengthLabel'>Page Size:</span>",
        },
        "sDom": '<"table_top"fl<"clear">>,<"tbl_tools"C<"clear">>,<"table_content"t>,<"table_bottom"iTp<"clear">>',
        "oTableTools": {
            "sSwfPath": "/Content/media/swf/copy_csv_xls_pdf.swf", // Set up media fie path
            "aButtons": ["copy", "csv", "pdf", "print"]
        }
    });
});

在您的视图中

@model IEnumerable<YourModel>

 <table class="display" id="data_tbl">
        <thead>
            <tr>
                <th>AA</th>
                <th>BB</th>             
            </tr>
        </thead>       
        <tbody>
            @foreach (var obj in YourModel)
            {
                <tr>
                    <td>
                        @obj.AAValue                      
                    </td>
                    <td>
                        @obj.BBValue
                    </td>

                </tr>
            }
        </tbody>
</table>

您实际上不需要使用完整的数据包包。只需使用jquery.dataTables.jsTableTools.jscopy_csv_xls_pdf.swf以及jquery.dataTables.css即可。您可以从下面下载它们:

http://www.datatables.net/download/

<强>更新 强类型数据表JS示例

(function setDataTable() {
    if (!window.jQuery) {
        setTimeout(setDataTable, 100);
        return;
    }
    var $table = $('#table-id');
    var dt = $table.dataTable({
        "aaSorting": [[0, "asc"]],
        "bProcessing": true,
        "bStateSave": true,
        "bServerSide": true,
        "bFilter": true,
        "sDom": 'T<"clear">lftipr',
        "aLengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
        "bAutoWidth": false,
        "sAjaxSource": "/Home/GetUsers", "oTableTools": { "sSwfPath": "/content/DataTables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf" },
        "fnServerData": function (sSource, aoData, fnCallback) {
            $.ajax({
                "dataType": 'json',
                "type": "POST",
                "url": sSource,
                "data": aoData,
                "success": fnCallback
            });
        },
        "aoColumnDefs": [{ "bSortable": false, "aTargets": [3] }, { "bVisible": false, "aTargets": [4, 5] }, { "bSearchable": false, "aTargets": [2] }, { "mRender": test, "aTargets": [1] }]
            , "fnCreatedRow": function (nRow, aData, iDataIndex) {
                $(nRow).attr('data-id', aData[0]);
            }
         , "oLanguage": { "sProcessing": "Bitte warten...", "sLengthMenu": "_MENU_ Einträge anzeigen", "sZeroRecords": "Keine Einträge vorhanden.", "sInfo": "_START_ bis _END_ von _TOTAL_ Einträgen", "sInfoEmpty": "0 bis 0 von 0 Einträgen", "sInfoFiltered": "(gefiltert von _MAX_  Einträgen)", "sInfoPostFix": "", "sSearch": "Suchen", "sUrl": "", "oPaginate": { "sFirst": "Erster", "sPrevious": "Zurück", "sNext": "Weiter", "sLast": "Letzter" } }
    });
})();