We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy.
Unfortunately, activation email could not send to your email. Please try again.

Get Custom JSON response from Grid Delete method.

Thread ID:

Created:

Updated:

Platform:

Replies:

130545 May 17,2017 09:35 AM Jun 1,2017 08:15 AM ASP.NET MVC 11
loading
Tags: Grid
zawar
Asked On May 18, 2017 01:18 AM

I want to get the conformation from the server side that my record is deleted or not. And I want to show the error to user. Actually syncfusion send the delete Ajax call internally. I am unable to get my custom json response from serverside.how i can get the response of my action?this is my MVC view code @(Html.EJ().Grid("Editing") .Datasource(ds => ds.Json((IEnumerable)ViewBag.dataSource).UpdateURL("NormalUpdate").InsertURL("NormalInsert").RemoveURL("Delete").Adaptor(AdaptorType.RemoteSaveAdaptor)) .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); }) .ToolbarSettings(toolbar => { toolbar.ShowToolbar().ToolbarItems(items => { items.AddTool(ToolBarItems.Add); items.AddTool(ToolBarItems.Edit); items.AddTool(ToolBarItems.Delete); items.AddTool(ToolBarItems.Update); items.AddTool(ToolBarItems.Cancel); }); }) .AllowPaging() .Columns(col => { col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(90).ValidationRules(v => v.AddRule("required", true).AddRule("number", true)).Add(); col.Field("CustomerID").HeaderText("Customer ID").Width(90).ValidationRules(v => v.AddRule("required", true).AddRule("minlength", 3)).Add(); col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).EditType(EditingType.Dropdown).Width(90).ValidationRules(v => v.AddRule("required", true)).Add(); col.Field("Freight").HeaderText("Freight").TextAlign(TextAlign.Right).Width(80).EditType(EditingType.Numeric).Format("{0:C}").NumericEditOptions(new EditorProperties() { DecimalPlaces = 2 }).ValidationRules(v => v.AddRule("range", "[0,1000]")).Add(); col.Field("ShipName").HeaderText("ShipName").Width(150).Add(); col.Field("ShipCountry").HeaderText("ShipCountry").Width(90).EditType(EditingType.Dropdown).Add(); }) .ClientSideEvents(eve => { eve.ActionComplete("complete").ActionBegin("begin").EndEdit("endEdit").EndAdd("endAdd"); }) ) }this is my MVC controller code public ActionResult Delete(int key) { string msg = string.Empty; bool success; try { success = ProgramDispatcher.Delete(key); msg = GenericMessage.GenericDeleteMessage; return JsonRetrun(true, key, msg); } catch (Exception ex) { msg = GenericMessage.ErrorMessage + ex.GetErrorCode(); return JsonRetrun(false, null, msg); } }
Farveen Sulthana Thameeztheen Basha [Syncfusion]
Replied On May 18, 2017 06:16 AM

Hi Zawar,   
  
Thanks for contacting Syncfusion Support.   
  
We have checked your requirement and we understand that you want to get the confirmation message whether the record gets deleted or not. For this purpose, you can use the events such as “ActionComplete” and “ActionFailure”. ActionComplete event is triggered after the successful completion of every action. ActionFailure event is triggered when the action fails. So you can make use of these events for your purpose.   
  
Please refer to the API references and code example.   
  
@(Html.EJ().Grid<object>("Grid")   
           .Datasource(ds => ds.Json((IEnumerable<object>)ViewBag.dataSource).UpdateURL("CellEditUpdate").InsertURL("CellEditInsert").RemoveURL("CellEditDelete").Adaptor(AdaptorType.RemoteSaveAdaptor))   
          .AllowPaging()   
          .ClientSideEvents(eve =>{eve.ActionComplete("complete");   
                                   eve.ActionFailure("failure");   
                          })   
   
          .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); })   
          .Columns(col =>   
              {   
                  .  .  .   
             }))   
       
    <script>   
        function complete(args) {   
           alert("success")   
        }   
        function failure(args) {   
                          var str = "";   
           str = ($($(args.error.error.responseText).find('b')[0]).text() + ":" + $(args.error.error.responseText).find('i').text());   
           window.alert(str)//alert message for the exception   
   
        }   
  
In the actionFailure event, on “args.error.error.responseText” you can get the responseText message  from the server side. Please refer to the screenshot.   
   
   
  

Regards, 
  
Farveen sulthana T   


zawar
Replied On May 18, 2017 07:10 AM

Thanks for your valuable response.

if you see my mvc controller action code. action failure method will not call at all, because i am using try catch. it always call the action complete method. i want to return my own custom message. 



Seeni Sakthi Kumar Seeni Raj [Syncfusion]
Replied On May 19, 2017 07:27 AM

Hi Zawar,  
 
We have achieved requirement “To retrieve the message from the server end after a success call using the Custom Adaptor”. We have extended the adaptor and later in the processResponse, message has been retrieved. Refer to the following code example.  
 
@{Html.EJ().Grid<object>("Grid") 
         .Datasource(ds => ds.Json((IEnumerable<object>)ViewBag.data) 
            .UpdateURL("/Home/ExternalUpdate") 
            .InsertURL("/Home/ExternalInsert") 
            .RemoveURL("/Home/ExternalDelete") 
            .Adaptor(AdaptorType.RemoteSaveAdaptor)) 
            .. .  
                    . ..  
        .ClientSideEvents(eve => 
        { 
            eve.ActionComplete("onComplete"); 
            eve.Load("onLoad"); 
        }) 
            .. . . 
                . . . 
} 
 
<script> 
    var customadaptor = new ej.remoteSaveAdaptor().extend({ 
        processResponse: function (data, ds, query, xhr, request, changes) { 
            if (!ej.isNullOrUndefined(data.msg)) 
                alert(data.msg); 
            return this.base.processResponse.apply(this, [data, ds, query, xhr, request, changes]); 
        } 
    }); 
    function onLoad(args) { 
        this.model.dataSource.adaptor = new customadaptor();//extend the adaptor 
    } 
 
</script> 
 
        public ActionResult ExternalDelete(int key) 
        { 
            . . . 
                 . . . 
            return Json(new { data = data, msg = "Unable To delete the record" }); 
        } 
 
 
We have prepared a sample that can be downloaded from the following location.  
 
 
Regards,  
Seeni Sakthi Kumar S. 


zawar
Replied On May 23, 2017 04:58 AM

Thanks for support.

Problem is fixed with this solution.

one more Issue is that, if i get an error message. my selected row is deleted from the grid.

now i want when i got an error message from server, selected row will not be deleted from the grid.



Seeni Sakthi Kumar Seeni Raj [Syncfusion]
Replied On May 24, 2017 03:24 AM

Hi Zawar,  
 
Since you are handling the failure actions using the catch in the server-end, Grid not updating the values back. To overcome this problem, we suggest to update the dataSource of the Grid in the ActionComplete event of the Grid. Refer to the following code example.  
 
@{Html.EJ().Grid<object>("Grid") 
         .Datasource(ds => ds.Json((IEnumerable<object>)Request.RequestContext.HttpContext.Session["data"]) 
            .UpdateURL("/Home/ExternalUpdate") 
            .InsertURL("/Home/ExternalInsert") 
            .RemoveURL("/Home/ExternalDelete") 
            .Adaptor(AdaptorType.RemoteSaveAdaptor)) 
          . . .  
             . . . 
        .ClientSideEvents(eve => 
        { 
            eve.ActionComplete("onComplete"); 
            eve.Load("onLoad"); 
        }) 
         . . . 
                  . . . 
} 
 
<script> 
    window.localData = [] 
    function onComplete(args) { 
        if (args.requestType == "delete") { 
            this.dataSource(ej.DataManager({ 
                json: localData,  
                insertUrl: "/Home/ExternalUpdate", 
                updateUrl: "/Home/ExternalInsert", 
                removeUrl: "/Home/ExternalDelete", 
                adaptor: new customadaptor() 
            })) 
        } 
         
    } 
    var customadaptor = new ej.remoteSaveAdaptor().extend({ 
        processResponse: function (data, ds, query, xhr, request, changes) { 
            if (!ej.isNullOrUndefined(data.msg)) { 
                window.localData = data.data; 
                alert(data.msg); 
            } 
            return this.base.processResponse.apply(this, [data, ds, query, xhr, request, changes]); 
        } 
    }); 
    function onLoad(args) { 
        this.model.dataSource.adaptor = new customadaptor();//extend the adaptor 
    } 
 
</script> 
 
        public ActionResult ExternalDelete(int key) 
        { 
            Orders ord = order.Where(or => or.OrderID == key).FirstOrDefault(); 
            var data = order; 
            if(key % 2 == 0) 
                return Json(new { data = data, msg = "Unable To delete the record" }); 
            order.Remove(ord); 
            return Json(new { data = data, msg = "Deleted the record" }); 
        } 
 
Regards,  
Seeni Sakthi Kumar S. 


zawar
Replied On May 24, 2017 03:35 AM

thanks for your response. actually i d't want to load the data again from the server. 
i just want to retain deleted line if error occurred.

Farveen Sulthana Thameeztheen Basha [Syncfusion]
Replied On May 25, 2017 08:34 AM

Hi Zawar, 
 
If you want to get the deleted line from the server, you can get by using “ActionFailure” event. In the ActionFailure event of the Grid,  you can get the deleted line while on refreshing the Grid on “refreshContent” method. Please refer to the code example and API references below:- 

@{Html.EJ().Grid<object>("Grid")  
         .Datasource(ds => ds.Json((IEnumerable<object>)Request.RequestContext.HttpContext.Session["data"])  
            .UpdateURL("/Home/ExternalUpdate")  
            .InsertURL("/Home/ExternalInsert")  
            .RemoveURL("/Home/ExternalDelete")  
            .Adaptor(AdaptorType.RemoteSaveAdaptor))  
          . . .   
             . . .  
        .ClientSideEvents(eve =>  
        {  
            eve.ActionComplete("onComplete");  
            eve.Load("onLoad"); 
            eve.ActionFailure("Failure")  
        })  
        . . .  
                 . . .  
        }  
  
<script>  
   window.localData = []  
        function onComplete(args) {  
            if (args.requestType == "delete") {  
                this.dataSource(ej.DataManager({  
                    json: localData,   
                    insertUrl: "/Home/ExternalUpdate",  
                    updateUrl: "/Home/ExternalInsert",  
                    removeUrl: "/Home/ExternalDelete",  
                    adaptor: new customadaptor()  
                }))  
            }  
          
        }  
        var customadaptor = new ej.remoteSaveAdaptor().extend({  
            processResponse: function (data, ds, query, xhr, request, changes) {  
                if (!ej.isNullOrUndefined(data.msg)) {  
                    window.localData = data.data;  
                    alert(data.msg);  
                }  
                return this.base.processResponse.apply(this, [data, ds, query, xhr, request, changes]);  
            }  
        });  
        function onLoad(args) {  
            this.model.dataSource.adaptor = new customadaptor();//extend the adaptor  
        } 
        function failure(args) { 
            var gridObj = $(".e-grid").data("ejGrid"); 
            gridObj.refreshContent(); 
             
        }  

Server side:- 
       public ActionResult ExternalDelete(int key) 
        { 
            Orders ord = order.Where(or => or.OrderID == key).FirstOrDefault(); 
            var data = order; 
            if (key % 2 == 0) 
                return Json(new { data = data, msg = "Unable To delete the record" }); 
            order.Remove(ord); 
            return Json(new { data = data, msg = "Deleted the record" }); 
        } 
    



Regards, 

Farveen sulthana T 


zawar
Replied On May 26, 2017 05:30 AM

Dear thanks for your replay, i d't want to reload the data. I just want to stop to grid from removing the data. it must contains the its state in case of delete failure. 

Farveen Sulthana Thameeztheen Basha [Syncfusion]
Replied On May 29, 2017 12:53 PM

Hi Zawar, 

According to your requirement, instead of reloading the data, we have retrived the deleted data using custom Adaptor.  In this sample we have used custom adaptor in “load” event and by extending the adaptor we have retrieved the deleted data Please refer to the code example  

<button id="btn" onclick="Save()">Click to save changes</button>  
<div id="Grid"></div>  
<script type="text/javascript">  
    $(function () {  
        var data =  @(Html.Raw(Json.Encode(@Request.RequestContext.HttpContext.Session["data"])));  
        $("#Grid").ejGrid({  
            dataSource: ej.DataManager({  
                json: data,  
                adaptor: new ej.remoteSaveAdaptor(),  
                batchUrl:"/Home/BatchUpdate"  
            }),  
            allowPaging:true,  
            actionFailure: "Failure",  
...  
            columns: [  
...  
            ],  
            load:"load",  
        });  
    });  
</script>  
  
<script type="text/javascript">  
    function load(args) {  
        this.model.dataSource.adaptor = new customAdaptor();  
    }  
  
    function Failure(args){  
         alert("delete failed. Please press the cancel icon to retrieve the deleted record");  
  
    }  
    var customAdaptor = new ej.remoteSaveAdaptor().extend({  
         
        batchRequest: function (dm, changes, e) {  
            var obj = []  
            obj.push(changes);  
            var res = {  
                changed: changes.changed,  
                added: changes.added,  
                deleted: changes.deleted,  
                action: "batch",  
                table: e.url,  
                key: e.key  
            };  
            return {  
                type: "POST",  
                url: dm.dataSource.batchUrl || dm.dataSource.crudUrl || dm.dataSource.url,  
                contentType: "application/json; charset=utf-8",  
                dataType: "json",  
                ejPvtData: obj,  
                data: JSON.stringify(res)  
            };  
        },  
        processResponse: function (data, ds, query, xhr, request, changes) {  
            var i;  
            var pvt = request && request.ejPvtData;  
            if(request != undefined){  
                for (i = 0; i < changes.added.length; i++)  
                    ej.JsonAdaptor.prototype.insert(ds, changes.added[i]);  
                for (i = 0; i < changes.changed.length; i++)  
                      
                    ej.JsonAdaptor.prototype.update(ds, "OrderID", changes.changed[i]);  
                for (i = 0; i < changes.deleted.length; i++)  
                    ej.JsonAdaptor.prototype.remove(ds, "OrderID", changes.deleted[i]);  
            } // updated the data after modification in grid  
            return this.base.processResponse.apply(this, [data, ds, query, xhr, request, changes]);  
        }  
  
    });  
  
    function Save(){  
        var grid = $("#Grid").ejGrid("instance");  
        grid.batchSave();  
    }  
  
</script>  
 [HomeController.cs]  
        public ActionResult BatchUpdate(List<EditableOrder> added,List<EditableOrder> changed, List<EditableOrder> deleted)  
        {  
                ...  
                
                if (deleted != null)  
                {  
                     
                        throw new Exception("TEST"); //making to fail the post when deleting action takes place  
                }  
                
...  
             
        }  

Please refer to the attached sample:- 


From the above code example by extending the adaptor we have retrieved the deleted data if deletion gets failed in server side.  
 
Note:  If we press the cancel icon after the post gets fails the deleted data will be retrieved from deletion.  
 
Refer the documentation link.  

 
Please let us know if you need further assistance.  

Regards, 

Farveen sulthana T

zawar
Replied On May 31, 2017 04:13 AM

thanks for your response. actually i am not the bulk delete and update. i am using single delete. this example is not full fill my requirement.  i just want to contain the delete row data in grid in case of server throw error.

Seeni Sakthi Kumar Seeni Raj [Syncfusion]
Replied On June 1, 2017 08:15 AM

Hi Zawar,  
 
Since you are handling the exception using the try/catch blocks, the Grid always hits a success call. Because of this, undeleted records will not be available back in the Grid. So, we suggest not to handle the Exception in the server-end. As a result of this, failure events will be triggered in the Grid. Henceforth, the Grid will show the earlier records back, in case of error in deletion.  
 
If you are insisted to use the try/catch blocks, use the solution provided to refresh the Grid on May 24, 2017. It will retrieve the data from the server end and update it back to the Grid using the dataSource method.  
 
Regards,  
Seeni Sakthi Kumar S. 


CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.

;