How to post custom content on delete?

How to post custom content on delete?

brewdevbrewdev Posts: 10Questions: 2Answers: 0

For editor updates (i.e., when it POSTs to the server), I have successfully implemented passing a custom form element called DatabaseName. I do this by adding to the editor upon initialization:

editor = new $.fn.dataTable.Editor({
    ...
}).add({
    name: "DatabaseName=" + (dbName || $(".ddlDatabases").val())
});

However, when I select a row and click the Delete button, it POSTs to the server BEFORE opening a dialog box (which contains a div with class "DTE_Action_Remove" which contains a nested Delete button). When it POSTs to the server BEFORE the delete dialog pops up, it DOES contain the custom DatabaseName element, but nothing actually happens on the server (until after the confirmation).

But, when I confirm the delete prompt by clicking the Delete button on the dialog, it POSTs to the server a second time. This is the action that is supposed to perform the actual delete, but on the second POST it no longer contains my custom element. How can I re-add my custom element to the actual POST action that performs the delete upon confirmation?

I have tried calling this on the ".DTE_Action_Remove button" click event, but it doesn't work:

editor.add({
    name: "DatabaseName=" + (dbName || $(".ddlDatabases").val())
});

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 51,422Questions: 1Answers: 7,754 Site admin

    However, when I select a row and click the Delete button, it POSTs to the server BEFORE opening a dialog box (which contains a div with class "DTE_Action_Remove" which contains a nested Delete button).

    Could you show me the full Editor and Editor API code you are using please? Specifically I need to know how you are calling the remove() method since by default it will show the lightbox before sending anything to the server.

    Generally I would suggest using ajax.data or preSubmit to add data to the object Editor sends to the server.

    Thanks,
    Allan

  • brewdevbrewdev Posts: 10Questions: 2Answers: 0
    edited March 3

    Actually, that was the first thing I tried, using the ajax.data, that is. However, it causes the New/Edit (INSERT/UPDATE) to fail.... with/without an error, depending on whether I pass this data as plain text or serialized JSON. However, when I simply remove ajax.data, it works as expected.

    I have indicated 3 lines of code that should be alternately uncommented to try various configurations. These places are where you will find "/* TODO:" comment blocks.

    If I do add ajax.data, yes, it does properly pass custom arguments to the server, which can be found in HttpContext.Current.Request.Form (C#). But the unwanted side-effect of it causing New/Edit/Delete to fail must then be overcome. Suggestions?

    BTW, this code has a bit of a legacy feel due to the server code being in a VB.NET ASMX web service. As such, I had to add function parseData to retrieve the pure JSON so it could be consumed by Datatables editor. You may wish to just remove that dataFilter. NOTE: This is very unlikely to be the cause of any problems because everything works if I merely do NOT post data in the ajax.data.

    Code will be forthcoming, due to size limits on Post Comment

  • brewdevbrewdev Posts: 10Questions: 2Answers: 0
    edited March 3

    JS Code

    var editor; // use a global for the submit and return data rendering in the examples
    
    var checkBoxCols = [
        "NeedTablet",
        "CompSpouseTicket",
        "Spouse_Reception",
        "Spouse_Gathering",
        "Spouse_Awards",
        "No_Jud_Capt",
        "Dietary",
        "ZeroComps",
        "RComps",
        "FComps",
        "S1Comps",
        "S2Comps",
        "IsNew"
    ];
    
    var textCol = function (label, name) {
        this.label = label;
        this.name = name || label;
    }
    
    var checkBoxCol = function (label, name) {
        this.label = label;
        this.name = name;
        this.type = "checkbox";
        this.separator = "|";
        this.options = [{ label: "", value: 1 }];
    }
    
    var checkBoxData = function (name) {
        this.data = name;
        this.render = function (data, type, row) {
            return renderCheckBox(data, type, row, name);
        };
        this.className = "dt-body-center editor-checkbox";
    }
    
    var dateData = function (name) {
        this.data = name;
        this.render = function (data) {
            return formatDate(data);
        }
    }
    
    function renderCheckBox(data, type, row, className) {
        if (type === "display") {
            return "<input type='checkbox' class='" + className + "'>";
        }
        return null;
    };
    
    function formatDate(data) {
        if (data !== undefined && data !== null) {
            return data.replace("T", " ");
        }
        return data;
    }
    
    $(document).ready(function () {
        editor = new $.fn.dataTable.Editor({
            ajax: {
                url: "/WebService.asmx/PostJudges",
                data: function (d) {
    
                    /* TODO: If I pass "DatabaseName=..." here, it successfully posts DatabaseName (Edit/New/Delete) 
                     * but it silently errors out on the server 
                     * and does not ISNERT/UPDATE/DELETE on SQL
                     */ 
                    //return "DatabaseName=" + $(".ddlDatabases").val();
    
                    /* TODO: If I pass serialized object here, it successfully posts DatabaseName (Edit/New/Delete)
                     * but it throws an error on the server, "Object reference not set to an instance of an object"
                     * and it does not INSERT/UPDATE/DELETE on SQL
                     */ 
                    //return JSON.stringify({
                    //    DatabaseName: $(".ddlDatabases").val()
                    //});
                },
                dataFilter: function (data) {
                    return parseData(data);
                }
            },
            table: "#tblEditJudges",
            fields: [
                new textCol("JudgeID"),
                new textCol("First Name", "FirstName"),
                new textCol("Last Name", "LastName"),
                new textCol("Email", "Email1"),
                new textCol("Judge Captain", "JudgeCaptain"),
                new textCol("Lodging Conf", "Lodging_Conf"),
                new textCol("CBC Info", "CBC_Info"),
                new checkBoxCol("NeedTablet", "NeedTablet"),
                new checkBoxCol("Comp Spouse Ticket", "CompSpouseTicket"),
                new textCol("Spouse Name", "Spouse_Name"),
                new checkBoxCol("Spouse Reception", "Spouse_Reception"),
                new checkBoxCol("Spouse Gathering", "Spouse_Gathering"),
                new checkBoxCol("Spouse Awards", "Spouse_Awards"),
                new checkBoxCol("No Jud Capt", "No_Jud_Capt"),
                new textCol("Shirt Size", "ShirtSize"),
                new checkBoxCol("Dietary", "Dietary"),
                new checkBoxCol("0Comps", "ZeroComps"),
                new checkBoxCol("RComps", "RComps"),
                new checkBoxCol("FComps", "FComps"),
                new checkBoxCol("S1Comps", "S1Comps"),
                new checkBoxCol("S2Comps", "S2Comps"),
                new textCol("Ticket Numbers", "Ticket_Numbers"),
                new textCol("Current Events", "Current_Events"),
                new textCol("y"), // CHANGE THIS FIELD NAME
                new textCol("New", "IsNew"),
                new textCol("Job Title", "Jobtitle"),
                new textCol("Company"),
                new textCol("Street"),
                new textCol("City"),
                new textCol("State"),
                new textCol("ZIP", "PostalCode"),
                new textCol("Country"),
                new textCol("Business"),
                new textCol("Cell"),
                new textCol("Home"),
                new textCol("Business Fax", "BusinessFax"),
                new textCol("BA_Comments"),
                new textCol("Judge Comments", "JudgeComments"),
                new textCol("Other Allergies", "OtherAllergies"),
                new textCol("Entered Date", "EnteredDate"),
                new textCol("Updated")
            ],
            formOptions: {
                inline: {
                    onBlur: 'submit'
                }
            }
        });
    
        /* TODO: If I include this add() then it posts DatabaseName, successfully performs New/Edit/Delete
         * but it does not post this data on the 2nd POST that it does after Delete confirmation
        */
        //}).add({
        //    // BEW Totally lame hack to append the DatabaseName to the form before the POST action (after edit)
        //    name: "DatabaseName=" + $(".ddlDatabases").val()
        //});
    
        $("#tblEditJudges").DataTable({
            dom: "Blfrtip",
            ajax: {
                url: "/WebService.asmx/GetJudges",
                contentType: "application/json",
                data: function (d) {
                    // passing extra data in the GET action is much easier. This gets prepended to the QueryString
                    return "DatabaseName=" + $(".ddlDatabases").val();
                },
                dataFilter: function (data) {
                    return parseData(data);
                }
            },
            columns: [
                {
                    data: "DT_RowId",
                    render: function (data) {
                        // hack to get DataTables to display the o/w hidden primary key column
                        return data.replace("row_", "");
                    }
                },
                { data: "FirstName", sClass: "editable" },
                { data: "LastName", sClass: "editable" },
                { data: "Email1" },
                { data: "JudgeCaptain", sClass: "editable" },
                { data: "Lodging_Conf" },
                { data: "CBC_Info" },
                new checkBoxData("NeedTablet"),
                new checkBoxData("CompSpouseTicket"),
                { data: "Spouse_Name" },
                new checkBoxData("Spouse_Reception"),
                new checkBoxData("Spouse_Gathering"),
                new checkBoxData("Spouse_Awards"),
                new checkBoxData("No_Jud_Capt"),
                { data: "ShirtSize" },
                new checkBoxData("Dietary"),
                new checkBoxData("ZeroComps"),
                new checkBoxData("RComps"),
                new checkBoxData("FComps"),
                new checkBoxData("S1Comps"),
                new checkBoxData("S2Comps"),
                { data: "Ticket_Numbers" },
                { data: "Current_Events" },
                { data: "y" },
                new checkBoxData("IsNew"),
                { data: "Type" },
                { data: "Jobtitle" },
                { data: "Company" },
                { data: "Street" },
                { data: "City" },
                { data: "State" },
                { data: "PostalCode" },
                { data: "Country" },
                { data: "Business" },
                { data: "Cell" },
                { data: "Home" },
                { data: "BusinessFax" },
                { data: "BA_Comments" },
                { data: "JudgeComments" },
                { data: "OtherAllergies" },
                new dateData("EnteredDate"),
                new dateData("Updated")
            ],
            // columnDefs tell it to order by multiple columns
            columnDefs: [
                {
                    // FirstName + LastName
                    targets: [1],
                    orderData: [1, 2]
                },
                {
                    // LastName + FirstName
                    targets: [2],
                    orderData: [2, 1]
                }
            ],
    
            //Rapid-tab control
            //https://editor.datatables.net/examples/inline-editing/tabControl.html            
            keys: {
                columns: ':not(:first-child)',
                keys: [9], // TAB key code
                editor: editor,
                editOnFocus: true
            },
            select: {
                style: 'os',
                selector: 'td:first-child'
            },
            buttons: [
                { extend: "create", editor: editor },
                { extend: "edit", editor: editor },
                { extend: "remove", editor: editor }
            ],
            rowCallback: function (row, data) {
                // Set the checked state of the checkbox in the table
                for (var x = 0; x < checkBoxCols.length; x++) {
                    $("input." + checkBoxCols[x], row).prop("checked", data[checkBoxCols[x]] == 1);
                }
            }
        });
    }
    
  • brewdevbrewdev Posts: 10Questions: 2Answers: 0

    JS Code PART II

    function parseData(data) {
        /* For DataTables Editor (used with ASMX) 
         * I had to parse the dataFilter response to eliminate the extra junk that Microsoft forces onto the response
         * when using an ASMX web service. DataTables expects PURE JSON, not JSON stuffed inside a "d" element or wrapped inside a <string></string> XML tag!
        */
        var obj = null;
        try {
            obj = JSON.parse(data);
        }
        catch (err) { }
        if (obj !== null && obj.d !== undefined) {
            data = obj.d;
        }
        var start = data.indexOf("{");
        var end = data.lastIndexOf("}") + Number(1);
        return data.substring(start, end);
    }
    
  • brewdevbrewdev Posts: 10Questions: 2Answers: 0

    C# Code

    <WebMethod(EnableSession:=True)>
    Public Function JudgesCore(DatabaseName As String, Method As MethodBase) As String
        Try
            'BEW DEBUG Hardcode DatabaseName to accommodate for when DataTables editor does not pass custom data on Delete confirmation
            DatabaseName = "WBC2020"
    
            If AdminAuth.IsAuth() AndAlso AdminAuth.Judges Then
                Dim request = HttpContext.Current.Request
                Using db = New Database("sqlserver", GetEventConnectionString(DatabaseName))
                    Dim response = New Editor(db, "Judges", "JudgeID") _
                        .Model(Of Judge)() _
                        .Field(New Field("JudgeID").Set(False)) _
                        .Field(New Field("FirstName")) _
                        .Field(New Field("LastName")) _
                        .Field(New Field("Email1")) _
                        .Field(New Field("JudgeCaptain")) _
                        .Field(New Field("Lodging_Conf")) _
                        .Field(New Field("CBC_Info")) _
                        .Field(New Field("NeedTablet")) _
                        .Field(New Field("CompSpouseTicket")) _
                        .Field(New Field("Spouse_Name")) _
                        .Field(New Field("Spouse_Reception")) _
                        .Field(New Field("Spouse_Gathering")) _
                        .Field(New Field("Spouse_Awards")) _
                        .Field(New Field("No_Jud_Capt")) _
                        .Field(New Field("ShirtSize")) _
                        .Field(New Field("Dietary")) _
                        .Field(New Field("ZeroComps")) _
                        .Field(New Field("RComps")) _
                        .Field(New Field("FComps")) _
                        .Field(New Field("S1Comps")) _
                        .Field(New Field("S2Comps")) _
                        .Field(New Field("Ticket_Numbers")) _
                        .Field(New Field("Current_Events")) _
                        .Field(New Field("y")) _
                        .Field(New Field("IsNew")) _
                        .Field(New Field("Type")) _
                        .Field(New Field("Jobtitle")) _
                        .Field(New Field("Company")) _
                        .Field(New Field("Street")) _
                        .Field(New Field("City")) _
                        .Field(New Field("State")) _
                        .Field(New Field("PostalCode")) _
                        .Field(New Field("Country")) _
                        .Field(New Field("Business")) _
                        .Field(New Field("Cell")) _
                        .Field(New Field("Home")) _
                        .Field(New Field("BusinessFax")) _
                        .Field(New Field("BA_Comments")) _
                        .Field(New Field("JudgeComments").Set(False)) _
                        .Field(New Field("OtherAllergies").Set(False)) _
                        .Field(New Field("EnteredDate").Set(False)) _
                        .Field(New Field("Updated").Set(False)) _
                        .Process(request) _
                        .Data()
    
                    ' Had to wrap this JSON in HttpUtility.HtmlDecode() because after posting an EDIT, 
                    ' the response becomes HTML encoded for some reason.
                    Return HttpUtility.HtmlDecode(JsonConvert.SerializeObject(response))
    
                End Using
            Else
                Return UnauthorizedResponse(Method)
            End If
        Catch ex As Exception
            Return GetErrorResponse(ex, Method)
        End Try
    End Function
    

    HTML

                        <table id="tblEditJudges" class="display" style="width:100%">
                            <thead>
                                <tr>
                                    <th>JudgeID</th>
                                    <th>FirstName</th>
                                    <th>LastName</th>
                                    <th>Email</th>
                                    <th>JudgeCaptain</th>
                                    <th>Lodging_Conf</th>
                                    <th>CBC_Info</th>
                                    <th>NeedTablet</th>
                                    <th>CompSpouseTicket</th>
                                    <th>Spouse_Name</th>
                                    <th>Spouse_Reception</th>
                                    <th>Spouse_Gathering</th>
                                    <th>Spouse_Awards</th>
                                    <th>No_Jud_Capt</th>
                                    <th>ShirtSize</th>
                                    <th>Dietary</th>
                                    <th>0Comps</th>
                                    <th>RComps</th>
                                    <th>FComps</th>
                                    <th>S1Comps</th>
                                    <th>S2Comps</th>
                                    <th>Ticket_Numbers</th>
                                    <th>Current_Events</th>
                                    <th>y</th>
                                    <th>New</th>
                                    <th>Type</th>
                                    <th>Jobtitle</th>   
                                    <th>Company</th>
                                    <th>Street</th>
                                    <th>City</th>
                                    <th>State</th>
                                    <th>PostalCode</th> 
                                    <th>Country</th>
                                    <th>Business</th>
                                    <th>Cell</th>
                                    <th>Home</th>
                                    <th>BusinessFax</th>
                                    <th>BA_Comments</th>
                                    <th>JudgeComments</th>
                                    <th>OtherAllergies</th>
                                    <th>EnteredDate</th>
                                    <th>Updated</th>
                                </tr>
                            </thead>
                        </table>
    
  • allanallan Posts: 51,422Questions: 1Answers: 7,754 Site admin
    Answer ✓

    Use this for your ajax.data:

    data: function (d) {
      d.database = $(".ddlDatabases").val();
    }
    

    As you will see from the ajax.data examples you need to modify the data that Editor wants to submit to the server. Otherwise Editor's data wouldn't be sent, and yes, the action would fail.

    Allan

  • brewdevbrewdev Posts: 10Questions: 2Answers: 0

    Yes, that's the trick. Thank you, sir.

Sign In or Register to comment.