This is a migrated thread and some comments may be shown as answers.

Datasource error event does not fire

3 Answers 604 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Tim
Top achievements
Rank 1
Tim asked on 06 Jan 2015, 05:20 PM
I've read many Telerik and stack overflow responses to this issue that still don't cover the answer to my question. Yes my error event handler is declared as part of my datasource configuration along with my requestEnd and change event handlers and they work. So my question is this, does the error event get canceled when the requestEnd event is declared?

My datasource is defined below for any critique you may have

<script>
    var model;
    var dataSource;

    $(document).ready(function () {

        dataSource = new kendo.data.DataSource({
            transport: {
                cache: false,
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                read: {
                    url: '/Telecom/Read',
                    type: 'POST',
                    complete: function (jqXHR, textStatus) {
                        
                        //$j('#message').text('Successful Read');
                        //$j('#dialog').dialog("option", "title", textStatus);
                        //$j('#dialog').dialog('open');
                    }
                },
                create: {
                    url: '/Telecom/Create',
                    type: 'POST',
                    complete: function (jqXHR, textStatus) {
                        //refreshGrid();
                        //$j('#message').text('Successful Create');
                        //$j('#dialog').dialog("option", "title", textStatus);
                        //$j('#dialog').dialog('open');
                         
                    }
                },
                update: {
                    url: '/Telecom/Update',
                    type: 'POST',
                    complete: function (jqXHR, textStatus) {
                        //refreshGrid();
                        //$j('#message').text('Successful Update');
                        //$j('#dialog').dialog("option", "title", textStatus);
                        //$j('#dialog').dialog('open');
                        
                    }
                },
                destroy: {
                    url: '/Telecom/Destroy',
                    type: 'POST',
                    complete: function (jqXHR, textStatus) {
                        //refreshGrid();
                        //$j('#message').text('Successful Delete');
                        //$j('#dialog').dialog("option", "title", textStatus);
                        //$j('#dialog').dialog('open');
                        
                    }
                },
            },
            error: onError,
            requestEnd: onRequestEnd,
            change: onChange,
            serverPaging: false,
            autoSync: false,
            schema: {
                model: {
                    id: 'Id',
                    fields: {
                        Id: { editable: false },
                        Name: { type: 'string', validation: { required: true } },
                        Category: { type: 'string', validation: { required: true } },
                        EquipmentType: { type: 'string', validation: { required: true } },
                        Description: { type: 'string' },
                        Length: { type: 'number', validation: { required: true } },
                        Height: { type: 'number', validation: { required: true } },
                        Width: { type: 'number', validation: { required: true } },
                        CanEditLength: { type: 'boolean', validation: { required: true } },
                        CanEditHeight: { type: 'boolean', validation: { required: true } },
                        CanEditWidth: { type: 'boolean', validation: { required: true } },
                        IsObsolete: { type: 'boolean', validation: { required: false } },
                        SortOrder: { type: 'number', validation: { required: false } }
                        // SortOrder: { type: 'number', validation: { min: 1, required: false } }
                    }
                }
            }
        });

        $('#grid').kendoGrid({
            dataSource: dataSource,
            sortable: true,
            //excel: {
            //    fileName: 'Telecommunication Data.xlsx',
            //    allPages: true
            //},
            save: onSave,
            dataBound: onDataBound,
            groupable: true,
            sortable: true,
            pageable: {
                refresh: true,
                pageSizes: [10, 25, 50, 100],
                pageSize: 25,
                page: 1,
            },
            scrollable: true,
            filterable: true,
            batch: false,
            height: 725,
            width: 800,
            toolbar: [{ name: 'add', text: 'Add New Telecom Record' }],
            columns: [
                { field: 'Id', title: 'Id', hidden: true },
                { field: 'Name', title: 'Name', width: '260px' },
                { field: 'Category', title: 'Category', width: '130px' },
                { field: 'EquipmentType', title: 'Type', width: '100px' },
                { field: 'Description', title: 'Description', width: '220px' },
                { field: 'Length', title: 'Length', width: '100px' },
                { field: 'Width', title: 'Width', width: '80px' },
                { field: 'Height', title: 'Height', width: '100px' },
                { field: 'CanEditLength', title: 'Can Edit Length', width: '160px' },
                { field: 'CanEditHeight', title: 'Can Edit Height', width: '160px' },
                { field: 'CanEditWidth', title: 'Can Edit Width', width: '160px' },
                { field: 'IsObsolete', title: 'Is Obsolete', width: '120px' },
                { field: 'SortOrder', title: 'Sort Order', width: '120px' },
                { command: { name: 'edit', text: "Edit", width: "160px", click: onEdit, change: onChange }, title: " ", width: "110px" },
                { command: ['destroy'], title: 'Delete', width: '110px' }],
            editable: {
                mode: 'popup',
                template: kendo.template($('#TelecommunicationsTemplate').html()),
                window: { title: 'Edit Power Equipment Details', width: 450, height: 550 }
            },
        });

        $('[class*=k-grid-add]').addClass('k-grid-edit')
        $(".k-pager-refresh").trigger('click');

        if ( $('#grid').data('kendoGrid').dataSource._page === undefined )
        {
            $('#grid').data('kendoGrid').dataSource._page = 1;
        }
            
    });

    function onDataBound(e) {
        $('.k-grid-Edit').find('span').addClass('k-icon k-edit');
        $('.k-grid-Delete').find('span').addClass('k-icon k-delete');
        //$('.k-grid-View').find('span').addClass('k-icon km-view');
    }

    //function onError(e, status) {
    //    if (e.errors) {
    //        var message = 'Errors:\n';
    //        $.each(e.errors, function (key, value) {
    //            if ('errors' in value) {
    //                $.each(value.errors, function () {
    //                    message += this + '\n';
    //                });
    //            }
    //        });

    //        // alert(message);
    //        $j('#message').text(message);
    //        $j('#dialog').dialog('option', 'title', 'Error');
    //        $j('#dialog').dialog('open');
    //    }
    //}

    function onError(e, status) {

        // Cancel changes on any grids on the page that are using this data source
        $('.k-grid').each(function (item) {
            var grid = $(this).data("kendoGrid");
            if (e.sender === grid.dataSource) {
                grid.cancelChanges();
            }
        });

        if (e.status === "customerror") {
            alert(e.errors);
        }
        else {
            alert("Generic server error.");
        }

    }

    function onSave(e) {
        e.model.Category = $('#Category option:selected').text();
        //if (e.model.Id === undefined || e.model.Id === null || e.model.Id === '') {
        //    e.model.Id = 0;
        //}

        if (e.model.Id === '') {
            e.model.Id = 0;
        }
    }

    function onChange(e) {

        var mye = e;
    }

    function onRequestEnd(e) {

        if (e.type !== "read") {

            e.sender.read();

            if (e.response.Errors !== undefined && e.response.Errors !== null && e.response.Errors !== '') {
                $j('#message').html(e.response.Errors);
                $j('#dialog').dialog("option", "title", 'Error');
                $j('#dialog').dialog('open');
            }

        }
    }

    function refreshGrid(e) {

        e.preventDefault = true;

        var mygrid = $("#grid").data("kendoGrid");
        //mygrid.dataSource.read(e.response.Data);
        e.sender.read();
        mygrid.refresh();
    }

</script>

3 Answers, 1 is accepted

Sort by
0
Kiril Nikolov
Telerik team
answered on 08 Jan 2015, 11:23 AM

Hello Timothy, 

The error event is not getting canceled when requestEnd event is declared. Please note that the requestEnd event will be fired even if there is an error with the request, however the error information is only available as part of the error event handler

Regards,
Kiril Nikolov
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Ben
Top achievements
Rank 1
answered on 08 May 2019, 01:08 PM

I'm having a similar problem.  I have declared a Datasource error handler and would like it to trigger when there is an error in the controller function.  I have looked all over the this forum and am yet to find a good answer.  I am using ASP.Net MVC with the default insert and edit functionality for the grid. There are some fields that are required by the SQL procedure I use and an error is thrown when they are submitted blank.  I am looking for a way to inform the user of the problem while still using the default insert and edit methods. Some sample code for my grid is below:

@(Html.Kendo().Grid<Intra.Common.Menu>()
            .Name("gridMenus")
            .ToolBar(tb => tb.Create())
            .Columns(columns =>
            {
                columns.Bound(mvm => mvm.MenuItemId).Hidden(true);
                columns.Bound(mvm => mvm.MenuName).Title("Menu Name").Width(200);
                columns.Bound(mvm => mvm.MenuPath).Title("Menu Path").Width(200);
                columns.Bound(mvm => mvm.MenuDescription).Title("Menu Description").Width(200);
                columns.Bound(mvm => mvm.MenuParentID).Title("Menu Parent ID").Width(200);
                columns.Bound(mvm => mvm.LowerLevelMenuParentID).Title("Lower Level Menu Parent ID").Width(200);
                columns.Bound(mvm => mvm.SortOrder).Title("Sort Order").Width(200);
                columns.Bound(mvm => mvm.IsDisplayed).Title("Is Displayed").Width(200);
                columns.Command(command => 
                {
                    command.Edit();
                }).Width(200);
            })
            .Pageable()
            .Reorderable(r => r.Columns(true))
            .Groupable()
            .Filterable()
            .Sortable()
            .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(50)
                        .Events(events => events.Error("error_handler").RequestEnd("onRequestEnd"))
                .Model(model => model.Id(mvm => mvm.MenuItemId))
                .Read(read => read.Action("getMenuItems", "Menu").Type(HttpVerbs.Get))
                .Create(create => create.Action("AddItem", "Menu"))
                .Update(update => update.Action("UpdateItem", "Menu"))
            )
        )

I am aware that the onRequestEnd function will still run when there is an error, I am just looking for a way to take the error into account.

If you need any additional information please let me know, and thank you for your time.

0
Tsvetina
Telerik team
answered on 10 May 2019, 08:03 AM
Hi Ben,

In the MVC Grid scenario, the response returned from the server has to contain the error message in an Errors field in order for the DataSource to recognize that there are any errors and to throw the Error event. It is best to construct a DataSourceResult object containing the error information:
var result = new DataSourceResult() {
    Errors = new { error = "fail", message="An error occurred..." }
};

Then, based on the content of the errors object, you can write your custom handling of the Error event:
<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            $.each(e.errors, function (key, value) {
                if (key == "message") {
                    alert(value);
                }
            });     
        }
    }
</script>


Regards,
Tsvetina
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
Grid
Asked by
Tim
Top achievements
Rank 1
Answers by
Kiril Nikolov
Telerik team
Ben
Top achievements
Rank 1
Tsvetina
Telerik team
Share this question
or