Rows disappeared from Grid on Delete fail

8 posts, 0 answers
  1. Hardeep
    Hardeep avatar
    5 posts
    Member since:
    Jul 2013

    Posted 17 Jul 2013 Link to this post

    Hi,

    In Kendo UI grid: When I press delete button and delete fails (because of foreign key constraints) still that row getting disappear from the Grid.




    1) .cshtml code as below (GRID)




    @(Html.Kendo().Grid(Model)
        .Name("Grid")
        .Columns(columns =>
        {
            //columns.Bound(p
    => p.ID).Width(35);
            columns.Bound(p => p.ClientName);//.Width(50);
            columns.Bound(p => p.ClientCode);//.Width(30);
            columns.Bound(p => p.Desc);//.Width(100);
            columns.Bound(p =>
    p.PrimaryContact);//.Width(80);
            //columns.Bound(p
    => p.PrimaryContact).Template(p =>
            //    @Html.ActionLink("Edit",
    "Edit", new { id=p.ID }))
            //   
    .ClientTemplate(Html.ActionLink("Edit", "Edit",
    new { Id = "id" }).ToHtmlString().Replace("id",
    "#=id#")).Width(30).Title("");
            columns.Command(command => {
    command.Edit(); command.Destroy(); });//.Width(40);  
            columns.Bound(p =>
    p.PrimaryContact).Template(p =>
                @Html.ActionLink("Spot Data", "../ViewSpotTimes/Index1",
    new { id = p.ID }))
                .ClientTemplate(Html.ActionLink("Spot Data", "../ViewSpotTimes/Index1",
    new { Id = "id"
    }).ToHtmlString().Replace("id", "#=id#")).Title("Spot Data");//.Width(20).Title("");
       })
                    .ToolBar(toolbar =>
                    {
                        toolbar.Create().Text("Add Client"); toolbar.Custom().Text("To csv").HtmlAttributes(new { id = "export"
    })
              .Url(Url.Action("Export", "Client"));
     
                        toolbar.Custom().Text("To excel").HtmlAttributes(new { id = "export"
    })
              .Url(Url.Action("ExportExcel", "Client"));
                    })
        .Editable(editable =>
    editable.Mode(GridEditMode.PopUp))
        .Selectable(selectable => selectable
         .Mode(GridSelectionMode.Multiple)
         .Type(GridSelectionType.Cell))
        .Navigatable()
        .Pageable()
        .Sortable()
             .Scrollable(scr => scr.Height(530))
         .ClientDetailTemplateId("template")
        //.Scrollable()
        .HtmlAttributes(new
    { style = "height:630px;" })
        .DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(500)
                 .Read(read => read.Action("HierarchyBinding_Employees", "Client"))
             .Events(events => events.Error("error_handlerPP"))
            .Model(model => model.Id(p =>
    p.ID))
            .Create(update => update.Action("EditingPopup_Create", "Client"))
            .Read(read => read.Action("EditingPopup_Read", "Client"))
            .Update(update => update.Action("EditingPopup_Update", "Client"))
            .Destroy(update => update.Action("EditingPopup_Destroy", "Client"))
            .Create("Create","Client")
            )
        .Events(events => events.DataBound("dataBound"))
    )
     




     




     




    Script as below




    <script type="text/javascript">
        function
    error_handlerPP(e) {
            e.preventDefault(e);
            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);
            }
        }
    </script>
     
     
    //Also I tried below Code
    <script type="text/javascript">
        var
    validationMessageTmpl1 = kendo.template($("#message").html());
     
        function
    error_handler1(args) {
           
            if
    (args.errors) {
                var
    grid = $("#Grid").data("kendoGrid");
                grid.one("dataBinding",
    function (e) {
                    e.preventDefault();   // cancel
    grid rebind if error occurs                            
                    for (var error in
    args.errors) {
                    alert("Not deleted Successfully! See Log for details")
                       
    showMessage1(grid.element, error, args.errors[error].errors);
                    }
                });
            }
        }
     
     
     
        function
    showMessage1(container, ClientName, errors) {
            //add
    the validation message to the form
            container.find("[data-valmsg-for=" + ClientName + "],[data-val-msg-for=" + ClientName + "]")
            .replaceWith(validationMessageTmpl1({
    field: ClientName, message: errors[0] }))
        }
        </script>
     




     




    Controller code as below




                [AcceptVerbs(HttpVerbs.Post)]
                public
    ActionResult EditingPopup_Destroy([DataSourceRequest] DataSourceRequest
    request, ClientModel client)
                {
                    if
    (client != null)//
    && ModelState.IsValid)
                    {
                        try
                        {
                           
    db.ClientModels.Remove(db.ClientModels.Find(client.ID));
                            db.SaveChanges();
                        }
                        catch
    (Exception ex)
                        {
     
                           
    ModelState.AddModelError("ClientName",
    Convert.ToString(ex.InnerException.InnerException.Message));
                        }
     
                    }
     
                    //return
    RedirectToAction("IndexKUI1");
                    return
    Json(new[] { client
    }.ToDataSourceResult(request, ModelState));
                    //return
    Json(ModelState.ToDataSourceResult());
                  
                    }
     




     
  2. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2311 posts

    Posted 17 Jul 2013 Link to this post

    Hello Hardeep,


    This is a quote from my answer in the support thread.

    Generally this is the default behavior of the Grid. As a workaround you could call the cancelChanges method of the Grid in the error event handler of the dataSource, which will restore the removed row if the delete operation was unsuccessful.
    E.g.
    function error_handler(e) {
        $("#grid").data("kendoGrid").cancelChanges();
        ...
    }

    I hope that this approach will work in the current scenario. I wish you a great day!


    As a side note, please post your questions only once, so we could provide you the best possible assistance. I wish you a great day!

     

    Regards,
    Dimiter Madjarov
    Telerik
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
  3. Dan
    Dan avatar
    173 posts
    Member since:
    Nov 2017

    Posted 13 Aug 2019 Link to this post

    Hi,

    My error_handler also handles the create and update errors and if I cancelChanges on those events it will cancel changes which is not what I want for create and update. How can I cancelChanges only on delete event and not on create and update.

  4. Alex Hajigeorgieva
    Admin
    Alex Hajigeorgieva avatar
    1081 posts

    Posted 15 Aug 2019 Link to this post

    Hello, Dan,

    One way you could achieve the desired error handler behaviour is by adding to the key that the error was caused by a Destroy operation and only then cancel the changes:

       // Destroy Action
      ModelState.AddModelError("destroy", "destroyError"); // add key so you can recognize the action in the error handler
       return Json(new [] { order }.ToDataSourceResult(request, ModelState));
     
      .DataSource(d=> {
       d.Ajax()
       .Events(e=>e.Error("onError"))
    <script>
       function onError(args) {
           var errors = args.errors;
           if (errors) {
               var grid = $("#grid").data("kendoGrid");
               var message = "";
               $.each(errors, function (key, value) {
                   if (key == "destroy") {
                       grid.cancelChanges(); // cancel changes only for the "destroy" key
                   }
                    
                   if ('errors' in value) {
                       $.each(value.errors, function () {
                           message += this + "\n";
                       });
                   }
               });
               kendo.alert(message);
           }
       }
     </script>

    Kind Regards,
    Alex Hajigeorgieva
    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.
  5. evadyyc
    evadyyc avatar
    2 posts
    Member since:
    Jan 2016

    Posted 30 Jan 2020 in reply to Alex Hajigeorgieva Link to this post

    I get the kendo alert showing correctly... but the grid still shows as the row having deleted.

    Quick work around is I've added a location.reload(); under the kendo.alert(message); as the data has not been removed from the DB

    However I feel like there's a missing part here as we should be able to delay the client side "pre delete"?

                });
                kendo.alert(message);
                location.reload();
            }
        }

  6. Preslav
    Admin
    Preslav avatar
    589 posts

    Posted 03 Feb 2020 Link to this post

    Hi Evadyyc,

    Generally speaking, the "location.reload();" reloads the page, and thus, any non-saved changes are disregarded. 

    Could you please confirm that invoking the "grid.cancelChanges();" method did not return the deleted row in the table of the Grid?

     

    Regards,
    Preslav
    Progress Telerik

    Get quickly onboarded and successful with your Telerik UI for ASP.NET MVC with the dedicated Virtual Classroom technical training, available to all active customers.
  7. evadyyc
    evadyyc avatar
    2 posts
    Member since:
    Jan 2016

    Posted 03 Feb 2020 in reply to Preslav Link to this post

    Yes I can confirm that the grid.cancelChanges() did not bring back the row.

    I noticed the row data is deleted before the javascript onError function fires if that helps?

  8. Preslav
    Admin
    Preslav avatar
    589 posts

    Posted 05 Feb 2020 Link to this post

    Hello Evadyyc,

    I tested the cancelChanges method in the error handler, and unfortunately, I was not able to replicate the problem. Could you please check the attached project and let me know what the differences with the scenario on your side are?

    I look forward to hearing from you.

     

    Regards,
    Preslav
    Progress Telerik

    Get quickly onboarded and successful with your Telerik UI for ASP.NET MVC with the dedicated Virtual Classroom technical training, available to all active customers.
Back to Top