File Upload on click of delete button in Datatable

File Upload on click of delete button in Datatable

agarnagarn Posts: 25Questions: 4Answers: 1
edited July 2019 in Free community support

Hi,

My requirement is either to delete rows that have been selected (works) OR to allow user to upload a file with lists of names to be deleted from the database. The code is ready. The only issue is how to allow file upload inside delete button. Using linq and C#. Can anyone help.

buttons: [
{ extend: "create", editor: oEditorCreate, formTitle: "Create new record" },
{ extend: "edit", editor: oEditor, formTitle: "Edit record" },
{
extend: "remove", editor: oEditor, formTitle: "Delete record",
formButtons: [
{ label: 'Delete', className: 'btn-danger', fn: function () { this.submit(); } },
{ label: 'Cancel', className: 'btn-primary', fn: function () { this.close(); } }

                   ],
                   formMessage: function (e, dt) {
                       var rows = dt.rows(e.modifier()).data().pluck('id');
                       var ids = rows.join(',');
                       var queryMsg;

                       if (rows.count() > 0) {
                           if (rows.count() == 1) {
                               queryMsg = "<p>Are you sure you want to delete " + rows.count() + " row?</p>";
                           }
                           else {
                               queryMsg = "<p>Are you sure you want to delete " + rows.count() + " rows?</p>";
                           }
                       } else {
                           queryMsg = "<div><span class='btn btn-success fileinput-button'><i class='glyphicon glyphicon-plus'></i><span>Add Configuration List</span><input id='fileupload' type='file' name='files[]' /></span><div id='files' class='files'></div></div><br/>";
                       }
                       return queryMsg;
                   }
               }
           ],

Thanks

Answers

  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954
    edited July 2019

    Maybe you can use this example as a start:
    https://editor.datatables.net/examples/extensions/import.html

    Instead of calling the selectColumns() function on line 94 you could create a function the builds the proper row-selector then calls remove(). Similar to what the selectColumns() function does when calling editor.create.

    Sorry I don't have more specifics. I actually just started working with the CSV Import example and it works well but I haven't written code to delete from a list.

    Kevin

  • agarnagarn Posts: 25Questions: 4Answers: 1

    Thanks Kevin. Let me try if that works.

  • agarnagarn Posts: 25Questions: 4Answers: 1
    edited August 2019

    Thanks Kevin. Your post helped a lot!
    I could accomplish the desired functionality (if aleast one checkbox is selected on click of delete button then it shows error message that these many rows will be deleted else if none of the checkbox is selected, it gives an option to upload an excel file data and deletes those names from DB) using:

    1) Extend the definition of delete button in datatable

    oTable = $('#myDataTable').DataTable({
    "sPaginationType": "full_numbers",
    "bProcessing": true,
    "bServerSide": true,
    "bJQueryUI": false,
    "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
    "iDisplayLength": 50,
    "sDom": 'lBfrt<"tableFooter"ip>',
    "aaSorting": [[1, 'asc']],
    "autoWidth": false,
    "oLanguage": {
    "sSearch": "Search all columns:"
    },
    "ajax": {
    "type": "POST",
    "url": '@Url.Action("GetDataTables")'
    },

            "columns": [
                { "name": "Id", "data": "id", "title": "Id", "orderable": false, "searchable": false, "visible": false, "editField": "id"},
                { "name": "Name", "data": "name", "title": "Name", "orderable": true, "searchable": true, "visible": true, "width": "29%", "editField": "name"  },
            ],
    
            buttons: [
                { extend: "create", editor: oEditor, formTitle: "Create new name" },
                { extend: "edit", editor: oEditor, formTitle: "Edit name"  },
                {
                    extend: "remove", editor: oEditor, formTitle: "Delete name",
                    formButtons: [
                        { label: 'Delete', className: 'btn-danger', fn: function () { this.submit(); } },
                        { label: 'Cancel', className: 'btn-primary', fn: function () { this.close(); } }
    
                    ],
                    formMessage: function (e, dt) {
                        var rows = dt.rows(e.modifier()).data().pluck('id');
                        var ids = rows.join(',');
                        var queryMsg;
    
                        if (rows.count() > 0) {
                            if (rows.count() == 1) {
                                queryMsg = "<p>Are you sure you want to delete " + rows.count() + " row?</p>";
                            }
                        } else {
                            uploadEditor.create({
                                title: 'Bulk Delete Names',
                                buttons: [{
                                    label: "Delete", className: "btn-danger",
                                        fn: function () {
                                            $.ajax({
                                                type: "POST",
                                                contentType: 'application/json',
                                                dataType: 'json',
                                                url: '@Url.Action("DeleteData")'
                                            }).done(function (status) {
                                                bootbox.alert(status, function () { window.location.href = "@Url.Content("~/Name")"; } );
                                            }).fail(function (status) {
                                                bootbox.alert(status, function () { window.location.href = "@Url.Content("~/Name")"; } );
                                            });
                                        }
                                    },
                                    { label: "Cancel", className: "btn-primary", fn: function () { this.close(); }
                                }]
                            });
                        }
                        return queryMsg;
                    }
                }
            ],
            select: {
                style: 'os',
                selector: 'td:first-child'
            },
            "order": [1, "asc"],
            initComplete: function () {
    
                $(function () {
                    $('[data-toggle="tooltip"]').tooltip()
                })
    
                // Name
                var nameColumn = this.api().column("Name:name");
                var nameSearchBox = $('<input type="text" class="form-control" placeholder="All" style="width:100%" />')
                    .appendTo($(nameColumn.footer()).empty())
                    .on('keyup change', function () {
                        var val = $(this).val();
                        nameColumn.search(val ? val : '', false, false).draw();
                    });
            }
        });
    

    2) Define the new editor

    //Upload Editor - triggered from the delete button when no checkbox is selected
    var uploadEditor = new $.fn.dataTable.Editor({
    ajax: {
    upload: {
    type: 'POST',
    contentType: 'application/json',
    dataType: 'json',
    url: '@Url.Action("UploadedNames")',
    complete: function (jqXHR, textStatus) {
    lastImageUploadTimeStamp = Math.round(Date.now() / 10000);
    },
    error: function (jqXHR, textStatus) {
    },
    cache: false
    },
    },
    fields: [{
    label: "Add Name List",
    name: "NameList",
    type: "upload",
    display: function (file_id) {
    var imageDisplayHTML;
    try {
    imageDisplayHTML = '<label for="' + file_id + '">' + file_id + '</label>';
    console.log("Excel file uploaded is: " + file_id);
    }
    catch (err) {
    imageDisplayHTML = '<label for="' + file_id + '">' + file_id + '</label>';
    console.log("Excel file uploaded is: " + file_id);
    }
    return imageDisplayHTML;
    }
    }]
    });

    3) create a method in controller

    [HttpPost]
    public ActionResult UploadedNames(string action, HttpPostedFileBase upload)
    {
    //desired functionality here with upload variable.
    }

    4) The main delete functionality of excel has been implemented under the controller
    public ActionResult DeleteData(datatableEditStruct<NameDataTableResult> myData)
    {
    }

  • agarnagarn Posts: 25Questions: 4Answers: 1

    Hi

    I am stuck here in another kind of functionality where this time I need an upload button and a multi-select list for cloning information. I wanted to use the above editor only by adding a select label to it but not sure how to turn its visibility on/off for 2 different buttons.
    Also, how will the values that are selected come into the method on controller side.

    Thanks

  • allanallan Posts: 63,522Questions: 1Answers: 10,473 Site admin

    The dependent() method can be useful to showing / hiding other fields based on the value of a specific field. See this example.

    Allan

  • agarnagarn Posts: 25Questions: 4Answers: 1

    Hi Allan,

    I have used dependent earlier but it is dependent on a column value. I need it to be dependent on an action. Eg: If datatable has 2 buttons namely, Edit and Delete, show a multi select list only when Edit button is clicked but not on delete.
    Can this be achieved using dependent?

    Thanks
    Agarn

This discussion has been closed.