I have a number of tables in an MVC.NET project that are created dynamically depending on the result of a query to a database. I would like to have a button in each div that contains each table that will export the table as a CSV file.

The set of divs containing tables is constructed in the following manner in the view:

            @for (int row = 0; row < Model.ActiveData.Count(); row++)
                            if (Model.ActiveData[row].ActiveDocuments.Select(a => a.DocumentId).Any())
                                <div class="some-class" id="active-document-@row">
                                            <div class="export-csv">
                                                <div class="form">
                                                    <button id="exportCsv" class="btn">Export CSV</button>
                                   @*Table to export to CSV*@


I would like to use javascript to export any given table in this set to csv. Using an example from a similar question about using Javascript to export csv data from a table, my current js looks something like this:

function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td)'),

        colDelim = '","',
        rowDelim = '"\r\n"',

        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row),
                $cols = $row.find('td');

            return $cols.map(function (j, col) {
                var $col = $(col),
                    text = $col.text();

                return text.replace(/"/g, '""'); // escape double quotes


            .split(tmpColDelim).join(colDelim) + '"',

        // Data URI
        csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

            'download': filename,
            'href': csvData,
            'target': '_blank'

$(".exportCsv").on('click', function (event) {
    exportTableToCSV.apply(this, [$('#active-document>table'), 'tabledata.csv']);

I am essentially wondering how I would pass in 'active-document-@row' to the exportCsv function.

Related posts

Recent Viewed