Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
280
Custom Delete Issue
posted

Hi,

I had to implement custom delete using Delete button. But I am getting an error, can anyone help me on this. Here is the code.

@using Infragistics.Web.Mvc
@using Microsoft.AspNetCore.Http
@model IQueryable<RateManagement.Models.RateIdentification>



<title>Rate Identification</title>


<style type="text/css">
    input.button-style {
        margin-top: 10px;
    }

    span.ui-iggrid-headertext {
        white-space: normal;
        text-overflow: ellipsis;
        word-break: break-word;
        font-size: 10pt !important;
    }

    .ui-iggrid-header {
        font-size: 10pt !important;
    }

    .ui-iggrid-footer {
        font-size: 10pt !important;
    }

    .ui-iggrid .ui-iggrid-tablebody td {
        font-size: 10pt;
    }

    .ui-iggrid .ui-iggrid-addrow td {
        font-size: 10pt;
    }

    .ui-iggrid .ui-iggrid-toolbar {
        font-size: 10pt;
    }

    .igx-grid__td span {
        white-space: nowrap !important;
        text-overflow: ellipsis !important;
        overflow: hidden !important;
    }

    .ui-iggrid tbody td {
        border-left: 1px solid #dadada;
        border-right: 1px solid #dadada;
    }
    /* .ui-igcombo-wrapper {
                                                                                        width: 300px !important;
                                                                                        font-size:12px !important;
                                                                                    }*/
</style>
<div style="padding:10px;">
    @(
        Html.Infragistics()
        .Grid(Model)
        .ID("Grid")
        .Height("800px")
        .Width("100%")
        .DefaultColumnWidth("150px")
        .AutoGenerateColumns(false)
        .AutoGenerateLayouts(false)
        .PrimaryKey("PrimaryKey")
        .AutoCommit(false)        
        .MergeUnboundColumns(true)
        .RenderCheckboxes(true)
        .Columns(column =>
        {
            column.For(x => x.PrimaryKey).HeaderText("").Width("0px").Hidden(true);
            column.For(x => x.RateIdentification1).HeaderText("Rate Identification").Width("150px");
            column.For(x => x.RateType).HeaderText("Rate Type").Width("70px");
            column.For(x => x.AllocationPercentFlag).HeaderText("Allocation Percent Flag").Width("150px");
            column.For(x => x.Otavalue).HeaderText("OTA Value").Width("100px").DataType("number");           
        })
        .Features(feature =>
        {
            feature.Updating()
            .StartEditTriggers(GridStartEditTriggers.DblClick)
            .EnableAddRow(false)
            .EnableDeleteRow(false)
            .EditMode(GridEditMode.Row)
            .ShowDoneCancelButtons(false)
            .EnableDataDirtyException(false)
            .ColumnSettings(cs =>
            {
                cs.ColumnSetting().ColumnKey("PrimaryKey");
                cs.ColumnSetting().ColumnKey("RateIdentification1");
                cs.ColumnSetting().ColumnKey("RateType").EditorType(ColumnEditorType.Text);
                cs.ColumnSetting().ColumnKey("AllocationPercentFlag").EditorType(ColumnEditorType.Text);
                cs.ColumnSetting().ColumnKey("Otavalue").EditorType(ColumnEditorType.Numeric);
			});                
            feature.RowSelectors();            
            feature.Selection().Mode(SelectionMode.Row).MultipleSelection(true).AllowMultipleRangeSelection(true);
            feature.ColumnFixing()
            .ShowFixButtons(false)
            .FixingDirection(ColumnFixingDirection.Left)
            .ColumnSettings(cs =>
            {
                cs.ColumnSetting().ColumnKey("RateIdentification1").AllowFixing(true);
                cs.ColumnSetting().ColumnKey("RateType").AllowFixing(false);
                cs.ColumnSetting().ColumnKey("AllocationPercentFlag").AllowFixing(false);
                cs.ColumnSetting().ColumnKey("Otavalue").AllowFixing(false);                
            });
            feature.Sorting().Type(OpType.Remote);
            feature.Paging().Type(OpType.Local);
            feature.Filtering().Type(OpType.Remote).Mode(FilterMode.Advanced).ColumnSettings(cs =>
            {
                cs.ColumnSetting().ColumnKey("RateIdentification1").AllowFiltering(true);
                cs.ColumnSetting().ColumnKey("RateType").AllowFiltering(false);                
            });

           
        })
        .DataSourceUrl(Url.Action("GetRateIdentification"))
        .UpdateUrl(Url.Action("SaveRateIdentification"))
        .DataBind()
        .Render()
        )
    <div id="addingOptions" class="explorer2 adding-Options col-lg-12 d-flex flex-wrap flex-lg-nowrap mt-5 justify-content-between">
        <div class="addNewRow addNewRow-option d-flex flex-wrap gap-2">
            <label for="RowsToadd">Rows to Add</label>
            <input id="RowsToadd" maxlength="2" type="text" value="1" style="width:30px"
                   onkeypress='javascript:return isNumber(event)' />
            <input id="addRow" type="button" value="Add New Row" class="ButtonClass shadow-sm btn btn-primary border" />
            <input id="selectRow" type="button" value="Select All Row" class="ButtonClass shadow-sm btn btn-primary border" />
            <input id="copyRow" type="button" value="Copy Rows" class="ButtonClass shadow-sm btn btn-primary border" />
            <input id="exportRow" type="button" value="Export" class="ButtonClass shadow-sm btn btn-primary border" />
            @*  <input type="button" id="saveChanges" class="changes-btn ButtonClass1 shadow-sm h-auto btn btn-success" value="Save Changes" />*@
            <input id="saveRow" type="button" value="Save Changes" class="ButtonClass shadow-sm btn btn-primary border" disabled="true" />
            <input type="button" id="undo" class="ButtonClass shadow-sm btn btn-primary border" value="Cancel Changes" />
            @* <input type="button" id="redo" class="ButtonClass shadow-sm btn btn-primary border" value="Redo" />*@
            <input id="deleteRow" type="button" value="Delete Rows" class="ButtonClass shadow-sm btn btn-primary border" />
            <input id="cancelRow" type="button" value="Cancel Changes" class="ButtonClass1" onclick="CancelChanges()" />
        </div>

    </div>
</div>
<script>
    var updates, lookupSecurity = [], loadingIndicator;
    let newRowID = null;

    function HandleGridCellUpdatedStart(evt, ui) {
        console.log(newRowID);
        if (ui.rowID != newRowID && ui.columnKey == "RateIdentification1") {
            //if not adding a row and the partner Name is trying to be updated, return right away
            return false;
        }
    }

    function editRowEnded(evt, ui) {
        if (ui.rowID == newRowID) {
            newRowID = null;
        }
    }
    function dataBound(evt, ui) {
        //alert('bound');
    }

    $("#exportRow11").click(function () {

        //alert('hi');
        $.ig.GridExcelExporter.exportGrid($("#Grid"), { fileName: 'CarType' }, {
            // The keys of the columns that will not be exported
            columnsToSkip: ["PrimaryKey"],
        });
    });

    $("#exportRow").on("click", function () {
        var currentdate = new Date();
        var datetime = currentdate.getDate() + "/"
            + (currentdate.getMonth() + 1) + "/"
            + currentdate.getFullYear() + ":"
            + currentdate.getHours() + ":"
            + currentdate.getMinutes() + ":"
            + currentdate.getSeconds();
        $.ig.GridExcelExporter.exportGrid($("#Grid"), {
            fileName: "CarType_" + datetime,
            // The keys of the columns that will not be exported
            columnsToSkip: ["PrimaryKey"]
        },
            {
                cellExporting: function (e, args) {
                    if (args.cellValue != null && args.cellValue instanceof Date) {
                        var date = args.cellValue;
                        date.setDate(date.getUTCDate());
                        date.setHours(date.getUTCHours());
                        args.xlRow.cells(args.columnIndex).value(date);
                    }
                },
            });
    });

    var isClicked = false;
    $("#Grid").on("iggridrowselectorsrowselectorclicked", function (evt, ui) {
        // Handle event

        if (!isClicked) {
            isClicked = true;
            setTimeout(() => {
                isClicked = false;
            }, 300);
            return;
        }

    });


    $("#Grid").on("iggridupdatingdatadirty", function (event, ui) {
        $("#Grid").igGrid("commit");
        updates = null;
    });
    function selectedRowsCellsValue() {
        var rowId;
        var rows = $("#Grid").igGridSelection("selectedRows");
        $.each(rows, function (ix, el) {
            rowId = el.element.attr("data-id");
            var cellValue = $("#Grid").igGrid("getCellValue", rowId, "RateIdentification1");
            alert(cellValue);
        });
    }
    $(document).delegate("#Grid", "focusin",
        function (e) {

            if ($("#pasteHelper").length > 0) {

                return;
            }

            var container = $(document.body);
            var containerDiv = $("<div></div>")
                .css({
                    "position": "fixed",
                    "top": -10000,
                    "left": -10000
                });
            //create textarea for handling paste event. Text area will be transparent.
            var textArea = $("<textarea id='pasteHelper'></textarea>")
                .css({
                    "opacity": 0,
                    "overflow": "hidden"
                })
                .appendTo(containerDiv);
            containerDiv.appendTo(container);

            textArea.on("paste", pasteHandler);
        }).on('keydown', function (evnt) {

            //handle grid's keydown event
            var ctrl = evnt.ctrlKey, key = evnt.keyCode;
            if (ctrl && key == 86 || evnt.shiftKey && key == 45) // Ctrl-V || Shift-Ins
            {
                //on paste (Ctrl+V) move focus to textarea
                $("#pasteHelper").focus();
            }            
        });

    //paste event handler for the textArea.
    function pasteHandler(event) {
        var data;

        //get clipboard data - from window.cliboardData for IE or from the original event's argumets.
        if (window.clipboardData) {
            window.event.returnValue = false;
            data = window.clipboardData.getData("text");
        } else {
            data = event.originalEvent.clipboardData.getData('text/plain');
        }

        //process the clipboard data
        var processedData = ProcessData(data);
        //alert(processedData);
        AddRecords(processedData);
    }
    function ProcessData(data) {
        var pasteData = data.split("\n");
        for (var i = 0; i < pasteData.length; i++) {
            pasteData[i] = pasteData[i].split("\t");

            // Check if last row is a dummy row
            if (pasteData[pasteData.length - 1].length == 1 && pasteData[pasteData.length - 1][0] == "") {
                pasteData.pop();
            }
            //remove empty data
            if (pasteData.length == 1 && pasteData[0].length == 1 && (pasteData[0][0] == "" || pasteData[0][0] == "\r")) {
                pasteData.pop();
            }
        }
        return pasteData;
    }


    function AddRecords(processedData) {
        var columns = getVisibleColumns();
        //alert(currentCell);
        var fRowID;
        $('#saveRow').prop('disabled', false);
        for (var i = 0; i < processedData.length; i++) {
            var curentDataRow = processedData[i];
            var rowData = {};
            for (var j = 0; j < columns.length; j++) {
                var currentCell = curentDataRow[j];
                var colKey = columns[j].key;

                if (colKey == "CreatedDate" || colKey == "CreatedEmployee" || colKey == "LastChangedDate" || colKey == "LastChangedDate") {
                    currentCell = ''
                }
                rowData[colKey] = currentCell;
            }

            $("#Grid").igGridUpdating("addRow", rowData);
        }

    }

    function getVisibleColumns() {
        var visibleCols = [];
        var columns = $("#Grid").igGrid("option", "columns");
        $(columns).each(function () {
            //if (this.hidden !== true) {
            visibleCols.push(this);
            //}
        });
        return visibleCols;
    }


    //Bind after initialization
    $(document).delegate("#Grid", "iggridupdatingeditcellstarting",
        function (evt, ui) {
            cellToCompareVal = ui.owner.grid.getCellValue(ui.rowID, "CreatedDate");
            // alert($(ui.owner.grid.getCellValue(ui.rowID, "CreatedDate")).length);
            if ((ui.columnKey == "RateIdentification1")
                && typeof (cellToCompareVal) !== "undefined" && $(ui.owner.grid.getCellValue(ui.rowID, "CreatedDate")).length > 0) {
                $('#saveRow').prop('disabled', false);
                return false;
            }
        }
    );

    // **********************************************
    $(document).on("iggridupdatingeditcellstarting", "#Grid", function (evt, ui) {
        // alert(ui.rowID);
        var regex = new RegExp(`^[A-Z0-9]{1,12}\\|[A-Z0-9]{1,4}\\|[0-9]{2}\\/[0-9]{2}\\/[0-9]{4}$`);
        // if the regex check returns true - the record has compsite key with the following format: ############|####|####-##-##
        // meaning that this is not a newly added row, since the composite key of newly added rows do not contain a date format at the end
        if (regex.test(ui.rowID) && (ui.columnKey == "RateIdentification1")) {
            $('#saveRow').prop('disabled', false);
            return false;
        }
    });

    function isNumber(evt) {
        var iKeyCode = (evt.which) ? evt.which : evt.keyCode
        if (iKeyCode != 46 && iKeyCode > 31 && (iKeyCode < 48 || iKeyCode > 57))
            return false;
        return true;
    }
    $("#saveRow").bind({
        click: function (e) {
            alert('save');
            $("#Grid").igGridUpdating("endEdit", true, true);
            $("#Grid").igGrid("saveChanges",
                function success() {
                    $('#txtMessage').css('background-color', 'LightBlue').css('color', 'DarkBlue').css('font-weight', 'bold').css('font-family', 'Courier New');
                    $("#Grid").igGrid("dataBind");
                },
                function error(jqXHR, textStatus, errorThrown) {
                    //alert(JSON.parse(jqXHR.responseText).ErrorMessage);
                    if (JSON.parse(jqXHR.responseText).ErrorMessage.contains("All")) {
                        $('#txtMessage').css('background-color', 'LightBlue').css('color', 'DarkBlue').css('font-weight', 'bold').css('font-family', 'Courier New');
                        $("#Grid").igGrid("dataBind");
                    }
                    else {
                        $('#txtMessage').css('background-color', 'DarkRed').css('color', 'White').css('font-weight', 'bold').css('font-family', 'Courier New');
                    }
                    txtMessage.value = JSON.parse(jqXHR.responseText).ErrorMessage;
                });
        }

    });

    function toggleAction(isSaved) {
        // actionToggled = true;
        this.event.stopPropagation();
        $("#Grid").igGridUpdating("endEdit", isSaved, true);
        //actionToggled = false;

    }
    function CancelChanges() {
        //alert('hi');
        $("#Grid").igGrid("rollback");
        $("#Grid").igGrid("commit");
        // $("#gridAccountCarType").igGrid("dataSourceObject", returnData).igGrid("dataBind");
        $("#Grid").igGrid("dataBind");
        txtMessage.value = "";
        $('#txtMessage').css('background-color', 'LightBlue').css('color', 'DarkBlue').css('font-weight', 'bold').css('font-family', 'Courier New');
    }
    // process events of buttons
    $("#deleteRow").igButton({
        labelText: $("#deleteRow").val(),
        click: function (e) {
            var rowId;
            var checkstr = confirm('Are you sure you want to delete row(s)?');
            if (checkstr == true) {
                $('#saveRow').prop('disabled', false);
                var rows = $('#Grid').igGridSelection('selectedRows');
                  console.log(rows);
                $.each(rows, function (ix, el) {
                    rowId = el.element.attr("data-id");
                    console.log(rowId);
                    $("#Grid").igGridUpdating("deleteRow", rowId);
                    console.log('completed');
                });

            }
            else {
                alert('false');
                return false;
            }
        }

    });

    //$.each(rows, function (ix, el) {
    //    rowId = el.element.attr("data-id");
    //      //alert(rowId);
    //}

    // //var rowIndex = $("#rowSelect").igNumericEditor("option", "value"),
    // //    tr = $("#gridAccountCarType").igGrid("rowAt", parseInt(rowIndex - 1)), pkValue;
    // //   //alert(rowIndex);
    // //if (!tr) return;
    // //pkValue = parseInt($(tr).attr("data-id"));
    //  //alert(rowId);
    // $("#gridAccountCarType").igGridUpdating("deleteRow", 1);
    //}

    //    }
    //});
    $("#cancelRow").on('igbuttonclick',
        function (e, args) {
            updates = $.extend({}, grid.data('igGrid').pendingTransactions());
            $.each(updates, function (index, transaction) {
                grid.igGrid("rollback", transaction.rowId, true);
            });

            //$("#redo").igButton("option", "disabled", false);
            //$("#undo").igButton("disable");
            //$("#saveChanges").igButton("disable");

            return false;
        }
    );
    //$("#cancelRow").igButton({
    //    labelText: $("#cancelRow").val(),
    //    click: function (e) {
    //        $('#saveRow').prop('disabled', true);
    //        var ds = new $.igGrid.DataSource({
    //            dataSource: gridObject
    //        });
    //        // alert(ds);
    //        $("#Grid").igGrid("option", "dataSource", ds);
    //        //$("#gridAccountCarType").igGrid("dataSourceObject", returnData).igGrid("dataBind");
    //    }
    //});
    $("#selectRow").igButton({
        labelText: $("#selectRow").val(),
        click: function (e) {
            var $grid = $("#Grid");
            var rows = $grid.igGrid("allRows");
            var rowId;
            if ($("#selectRow").val() == "Select All Row") {
                document.getElementById("selectRow").value = "Unselect All Row";
                //      Loop through each row in the grid.
                $.each(rows, function (index, row) {
                    $grid.igGridSelection('selectRow', index);
                });
            }
            else if ($("#selectRow").val() == "Unselect All Row") {
                document.getElementById("selectRow").value = "Select All Row";
                //      Loop through each row in the grid.
                $('#Grid').igGridSelection('clearSelection');
            }
        }
    });

    $("#unselectRow").igButton({
        labelText: $("#unselectRow").val(),
        click: function (e) {
            $('#Grid').igGridSelection('clearSelection');
            var $grid = $("#Grid");
            var rows = $grid.igGrid("allRows");
            var rowId;
            //      Loop through each row in the grid.
            $.each(rows, function (index, row) {
                rowId = $(row).attr("data-id");
            });
        }
    });
    $("#copyRow").igButton({
        labelText: $("#copyRow").val(),
        click: function (e) {
            $('#saveRow').prop('disabled', false);
            var rows = $('#Grid').igGridSelection('selectedRows');
            let i = 0;
            $.each(rows, function (ix, el) {
                rowId = el.element.attr("data-id");
                let pk = $("#Grid").data('igGrid').dataSource._data.length + 1 + i;
                var rowObj = {
                    "PrimaryKey": pk,
                    "RateIdentification1": $("#Grid").igGrid("getCellValue", rowId, "RateIdentification1"),
                    "RateType": $("#Grid").igGrid("getCellValue", rowId, "RateType"),
                    "AllocationPercentFlag": $("#Grid").igGrid("getCellValue", rowId, "AllocationPercentFlag"),
                    "Otavalue": $("#Grid").igGrid("getCellValue", rowId, "Otavalue"),                    
                };
                i = i + 1;
                $("#Grid").igGridUpdating("addRow", rowObj);
            });

        }
    });
    $("#addRow").igButton({
        labelText: $("#addRow").val(),
        click: function (e) {
            $('#saveRow').prop('disabled', false);
            if (RowsToadd.value == "") {
                RowsToadd.value = 1;
            }
            else if (RowsToadd.value > 50) { RowsToadd.value = 50; }
            for (var i = 0; i < RowsToadd.value; i++) {
                let pk = $("#Grid").data('igGrid').dataSource._data.length + 1 + i;
                var rowObj = {
                    "PrimaryKey": pk,
                    "RateIdentification1": '',
                    "RateType": '',
                    "AllocationPercentFlag": '',
                    "Otavalue": '',
                   
                };
                $("#Grid").igGridUpdating("addRow", rowObj);
            }
        }
    });

    $(document).on("iggridrowselectorsrowselectorclicked", "#Grid", function (evt, ui) {

        // gets the keys of the columns which are set to be read only
        var readOnlyColumnsKeys = $("#Grid").igGridUpdating('option', 'columnSettings').filter(setting => setting.readOnly).map(setting => setting.columnKey);

        // gets the currently selected record

        // please keep in mind that ui.rowKey is a string, so if your primary keys are numbers you should convert it to number as in the following line
        var record = $("#Grid").igGrid("findRecordByKey", +ui.rowKey);

        // creates an array of objects that contain the key of the column that is read only and the value
        var readOnlyColumnsKeysAndValues = [];

        readOnlyColumnsKeys.forEach(key => {
            readOnlyColumnsKeysAndValues.push({
                columnKey: key,
                value: record[key]
            });
        });

        // creates a Nested Blocks Template
        var template = '{{each ${items}}}' +
            '<tr><td><b>${items.columnKey}:</b></td>' + '<td>${items.value}</td></tr>' +
            '{{/each}}';

        var result = $.ig.tmpl(template, {
            items: readOnlyColumnsKeysAndValues
        });

        //  $('#resultTable').html(result);

        //  $("#dialog").igDialog("open");
    });

    $(document).on("iggridupdatingeditrowended", "#Grid", function (evt, ui) {
        var editedRowElement = $("#Grid").igGrid("rowById", ui.rowID);
        var allRows = $("#Grid").igGrid("rows");
        var editedRowElementIndex = allRows.index(editedRowElement);
        // alert('ggg');
        $("#Grid").igGridUpdating("updateRow", ui.rowID, { Index: editedRowElementIndex });
        //$("#gridAccountCarType").igGridUpdating("addRow", ui.rowID, {Index: editedRowElementIndex});
    });
               
</script>




public partial class RateIdentification :{
public int PrimaryKey { get; set; }
public string RateIdentification1 { get; set; }
public string RateType { get; set; }
public string AllocationPercentFlag { get; set; }
public short Otavalue { get; set; }
}

{"PrimaryKey":10001,"RateIdentification1":"19U","RateType":"F","AllocationPercentFlag":"N","Otavalue":0}
{"PrimaryKey":10002,"RateIdentification1":"22U","RateType":"F","AllocationPercentFlag":"N","Otavalue":0}

I am getting at Delete Row button click- Uncaught Error: The specified record or property was not found. Verify the criteria for your search and adjust them if necessary.

Parents
No Data
Reply Children
No Data