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

Rows disappeared from Grid on Delete fail

7 Answers 1006 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Hardeep
Top achievements
Rank 1
Hardeep asked on 17 Jul 2013, 10:35 AM
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());
              
                }
 




 

7 Answers, 1 is accepted

Sort by
0
Dimiter Madjarov
Telerik team
answered on 17 Jul 2013, 01:54 PM
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!
0
Dan
Top achievements
Rank 1
Iron
Iron
Veteran
answered on 13 Aug 2019, 12:06 PM

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.

0
Alex Hajigeorgieva
Telerik team
answered on 15 Aug 2019, 09:06 AM
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.
0
evadyyc
Top achievements
Rank 2
answered on 30 Jan 2020, 10:06 PM

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();
        }
    }

0
Preslav
Telerik team
answered on 03 Feb 2020, 02:08 PM

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.
0
evadyyc
Top achievements
Rank 2
answered on 03 Feb 2020, 03:36 PM

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?

0
Preslav
Telerik team
answered on 05 Feb 2020, 01:00 PM

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.
Tags
Grid
Asked by
Hardeep
Top achievements
Rank 1
Answers by
Dimiter Madjarov
Telerik team
Dan
Top achievements
Rank 1
Iron
Iron
Veteran
Alex Hajigeorgieva
Telerik team
evadyyc
Top achievements
Rank 2
Preslav
Telerik team
Share this question
or