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.

Duplicate row in batch editing with multiple rows insert

Thread ID:

Created:

Updated:

Platform:

Replies:

129744 Mar 31,2017 10:21 AM Apr 6,2017 03:31 AM ASP.NET MVC 7
loading
Tags: Grid
CLAUDIO RICCARDI
Asked On March 31, 2017 10:21 AM

Hi,

I have the following grid:

                            @(Html.EJ().Grid<SlimHub.Models.QuoteSimulationPlantCost>("QuoteSimulationPlantCostsGrid")
                      .Datasource(ds => ds.Json((IEnumerable<QuoteSimulationPlantCost>)Model.QuoteSimulationPlantCosts.ToList()).UpdateURL("../PlantCostEqUpdate").InsertURL("../PlantCostEqInsert").RemoveURL("../PlantCostEqDelete").BatchURL("../PlantCostBatchUpdate").Adaptor(AdaptorType.RemoteSaveAdaptor))
                      .ShowSummary()
                        .SummaryRow(row =>
                        {
                            row.Title("Totale").SummaryColumns(col => { col.SummaryType(SummaryType.Sum).Format("{0:C}").DisplayColumn("TotalPrice").DataMember("TotalPrice").Add(); }).Add();
                        })
                      .EditSettings(edit =>
                      {
                          edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch);
                      })
                      .Locale("it-IT")
                      .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);
                          }).CustomToolbarItems(
                              new List<object>() {
                                  //new Syncfusion.JavaScript.Models.CustomToolbarItem() {TemplateID = "#Details"},
                                  new Syncfusion.JavaScript.Models.CustomToolbarItem() {TemplateID = "#Details"}});
                      })
                      .AllowResizing()
                      .AllowTextWrap(true)
                      .Columns(col =>
                      {
                          col.Field("PlantCostId").HeaderText("ID").HeaderTextAlign(TextAlign.Center).IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(40).Visible(true).AllowEditing(false).Add();
                          col.Field("QuoteSimId").HeaderText("ID Simulazione").HeaderTextAlign(TextAlign.Center).DefaultValue(Model.QuoteSimId).Width(100).Visible(true).AllowEditing(false).Add();
                          col.Field("EquipmentId").HeaderText("Attrezzatura").ForeignKeyField("EquipmentId").ForeignKeyValue("EquipmentDesc").DataSource((IEnumerable<object>)ViewBag.Equipments).HeaderTextAlign(TextAlign.Center).Width(80).Add();
                          col.Field("Quantity").HeaderText("Quantità").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:n1}").EditType(EditingType.Numeric).NumericEditOptions(new Syncfusion.JavaScript.Models.EditorProperties() { DecimalPlaces = 2, MaxValue = 99999999.99, Locale = "it-IT", MinValue = 0 }).Width(30).Add();
                          col.Field("UnitPrice").HeaderText("Prezzo Unitario").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").EditType(EditingType.Numeric).NumericEditOptions(new Syncfusion.JavaScript.Models.EditorProperties() { DecimalPlaces = 2, MaxValue = 99999999.99, Locale = "it-IT", MinValue = 0 }).Width(30).Add();
                          col.Field("TotalPrice").HeaderText("Prezzo Totale").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").AllowEditing(true).Width(30).Add();
                          //col.Field("TotalPrice").HeaderText("Prezzo Totale").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").AllowEditing(false).Width(80).Add();
                          col.Field("Annotations").HeaderText("Note").HeaderTextAlign(TextAlign.Center).Width(80).Add();
                      })
                      .ClientSideEvents(eve =>
                      {
                          eve.ActionComplete("PlantComplete");
                          eve.Create("PlantGridCreate");
                          eve.ToolbarClick("PlantToolBarClick");
                          eve.CellEdit("PlantCostsCellEdit");
                          eve.CellSave("PlantCostsCellSave");
                          eve.QueryCellInfo("CalculatePlantCostsTotalPrice");
                          eve.BeforeBatchSave("RefreshPlantCostsGrid");
                      })
                            )

***************************
Controller Batch Update Method
***************************
public ActionResult PlantCostBatchUpdate(string action, List<QuoteSimulationPlantCost> added, 
            List<QuoteSimulationPlantCost> changed, List<QuoteSimulationPlantCost> deleted, int? key)
        {
            if (added != null)
            {
                foreach (QuoteSimulationPlantCost qspc in added)
                {
                    db.QuoteSimulationPlantCosts.Add(qspc);
                }
            }
            else if (changed != null)
            {
                foreach (QuoteSimulationPlantCost qspc in changed)
                {
                    qspc.TotalPrice = qspc.Quantity * qspc.UnitPrice;
                    db.Entry(qspc).State = EntityState.Modified;
                }
            }
            else if (deleted != null)
            {
                foreach (QuoteSimulationPlantCost qspc in deleted)
                {
                    QuoteSimulationPlantCost quotePlantCost = db.QuoteSimulationPlantCosts.Find(qspc.PlantCostId);
                    db.QuoteSimulationPlantCosts.Remove(quotePlantCost);
                }
            }
            db.SaveChanges();

            var data = db.QuoteSimulations.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

---------------------------------------

When I add multiple rows (for example 4 rows) and click on the SAVE button, the 4 rows are added to the database but the last row has the same values of the first row added.

The attached file contains some screenshots that explains better the problem.

Some other details:

1) If I trigger the BeforeBatchSave event, the args parameter contains the added array with the correct 4 rows. When the added file is passed to the Controller method, it contains the two rows with the same values.

thanks.

Attachment: issue_a7835aad.zip

Jayaprakash Kamaraj [Syncfusion]
Replied On April 3, 2017 08:21 AM

Hi Claudio, 

Thank you for contacting Syncfusion support. 

While using BatchEdit in Grid we need to use only BatchURL to perform CRUD operations in server side. So , we suggest you remove InsertURL, UpdateURL and DeleteURL in your sample. Also, we have created a sample with your code example but we were unable to reproduce the issue at our end.  

Please share the following information to find the cause of the issue.  
                                                                                                                
  1. Is there any script error or exception thrown in your project? If so, attach a screenshot for your stack trace.  
  2. Check whether you have given same primary-key field value for first and last row.
  3. Share the video to show the issue.
  4. Grid rendering full code example both client and server.
  5. Essential studio and browser version details
  6. An issue reproducing sample if possible or replicate the issue in the following sample

 
Regards, 

Jayaprakash K. 


CLAUDIO RICCARDI
Replied On April 3, 2017 11:24 AM

I have removed code reference to the other methods but the ploblem is still present.

Is there any script error or exception thrown in your project? If so, attach a screenshot for your stack trace.  
No, no error or exception on the console

Check whether you have given same primary-key field value for first and last row.
No, primary key ID is autogenerated from SQL Server auto increment counter.

Share the video to show the issue.
See attachment

Grid rendering full code example both client and server.
CLIENT

                            @(Html.EJ().Grid<SlimHub.Models.QuoteSimulationPlantCost>("QuoteSimulationPlantCostsGrid").Datasource(ds => ds.Json((IEnumerable<QuoteSimulationPlantCost>)Model.QuoteSimulationPlantCosts.ToList()).BatchURL("../PlantCostBatchUpdate").Adaptor(AdaptorType.RemoteSaveAdaptor))
                      .ShowSummary()
                        .SummaryRow(row =>
                        {
                            row.Title("Totale").SummaryColumns(col => { col.SummaryType(SummaryType.Sum).Format("{0:C}").DisplayColumn("TotalPrice").DataMember("TotalPrice").Add(); }).Add();
                        })
                      .EditSettings(edit =>
                      {
                          edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch);
                      })
                      .Locale("it-IT")
                      .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);
                          }).CustomToolbarItems(
                              new List<object>() {
                                  //new Syncfusion.JavaScript.Models.CustomToolbarItem() {TemplateID = "#Details"},
                                  new Syncfusion.JavaScript.Models.CustomToolbarItem() {TemplateID = "#Details"}});
                      })
                      .AllowResizing()
                      .AllowTextWrap(true)
                      .Columns(col =>
                      {
                          col.Field("PlantCostId").HeaderText("ID").HeaderTextAlign(TextAlign.Center).IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(40).Visible(true).AllowEditing(false).Add();
                          col.Field("QuoteSimId").HeaderText("ID Simulazione").HeaderTextAlign(TextAlign.Center).DefaultValue(Model.QuoteSimId).Width(100).Visible(false).AllowEditing(false).Add();
                          col.Field("EquipmentId").HeaderText("Attrezzatura").ForeignKeyField("EquipmentId").ForeignKeyValue("EquipmentDesc").DataSource((IEnumerable<object>)ViewBag.Equipments).HeaderTextAlign(TextAlign.Center).Width(80).Add();
                          col.Field("Quantity").HeaderText("Quantità").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:n1}").EditType(EditingType.Numeric).NumericEditOptions(new Syncfusion.JavaScript.Models.EditorProperties() { DecimalPlaces = 2, MaxValue = 99999999.99, Locale = "it-IT", MinValue = 0 }).Width(30).Add();
                          col.Field("UnitPrice").HeaderText("Prezzo Unitario").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").EditType(EditingType.Numeric).NumericEditOptions(new Syncfusion.JavaScript.Models.EditorProperties() { DecimalPlaces = 2, MaxValue = 99999999.99, Locale = "it-IT", MinValue = 0 }).Width(30).Add();
                          col.Field("TotalPrice").HeaderText("Prezzo Totale").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").AllowEditing(true).Width(30).Add();
                          col.Field("Annotations").HeaderText("Note").HeaderTextAlign(TextAlign.Center).Width(80).Add();
                      })
                      .ClientSideEvents(eve =>
                      {
                          eve.ActionComplete("PlantComplete");
                          eve.Create("PlantGridCreate");
                          eve.ToolbarClick("PlantToolBarClick");
                          eve.CellEdit("PlantCostsCellEdit");
                          eve.CellSave("PlantCostsCellSave");
                          eve.QueryCellInfo("CalculatePlantCostsTotalPrice");
                          eve.BeforeBatchSave("RefreshPlantCostsGrid");
                      })
                            )

SERVER:

        public ActionResult PlantCostBatchUpdate(string action, List<QuoteSimulationPlantCost> added, 
            List<QuoteSimulationPlantCost> changed, List<QuoteSimulationPlantCost> deleted, int? key)
        {
            if (added != null)
            {
                foreach (QuoteSimulationPlantCost qspc in added)
                {
                    db.QuoteSimulationPlantCosts.Add(qspc);
                }
            }
            else if (changed != null)
            {
                foreach (QuoteSimulationPlantCost qspc in changed)
                {
                    qspc.TotalPrice = qspc.Quantity * qspc.UnitPrice;
                    db.Entry(qspc).State = EntityState.Modified;
                }
            }
            else if (deleted != null)
            {
                foreach (QuoteSimulationPlantCost qspc in deleted)
                {
                    QuoteSimulationPlantCost quotePlantCost = db.QuoteSimulationPlantCosts.Find(qspc.PlantCostId);
                    db.QuoteSimulationPlantCosts.Remove(quotePlantCost);
                }
            }
            db.SaveChanges();

            var data = db.QuoteSimulations.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

Essential studio and browser version details
Version 14.4460.0.15 - Browser Chrome ver. 57.0.2987.133


Attachment: issue_2b663fa7.zip

CLAUDIO RICCARDI
Replied On April 4, 2017 06:01 AM

After some debugging, I have seen that if I disable the CellSave event, the problem disappears.

The client javascript function called is this:
GRID EVENT: eve.CellSave("PlantCostsCellSave");        

function PlantCostsCellSave(args){        

     this.model.columns[2].dataSource = @Html.Raw(Json.Encode((IEnumerable)ViewBag.Equipments));//EquipmentId column        

     var gridObj = $("#QuoteSimulationPlantCostsGrid").data("ejGrid");        
     var index = gridObj.selectedRowsIndexes;               
     if (args.columnName == "EquipmentId") {            
          $("#QuoteSimulationPlantCostsGrid").ejWaitingPopup("show")//show popup            
          var eqId = args.value.value;            
          $.ajax({                
               type: "POST",                
               async: false,                
               url: '@Url.Action("GetEquipmentUnitPrice", "Equipment")',                
               contentType: "application/json; charset=utf-8",                
               dataType: "json",                
               data: JSON.stringify({ "EquipmentId": eqId }),                
               success: function(data) {                    
                              $("#QuoteSimulationPlantCostsGrid").ejWaitingPopup("hide")//hide popup                    
                              var number = parseFloat(data);                    
                              gridObj.setCellValue(index, "UnitPrice", number);                    
                              var quantity = 0;                    
                              if (args.rowData.Quantity != null) {                        
                                   quantity = args.rowData.Quantity.toString();                        
                                   quantity = quantity.replace(/,/g,'.');                        
                                   var res = parseFloat(quantity)*parseFloat(data);                        
                                   gridObj.setCellValue(index, "TotalPrice", res);                    
                              }                
               },                
               error: function (result) {                    
                         $("#QuoteSimulationPlantCostsGrid").ejWaitingPopup("hide")//hide popup                    
                         alert(result.statusText);                
               }            
          });        
     }        
     if (args.columnName == "Quantity") {...} 
       
     updatePlantTotals();        
     updateTotals();    }

It seems that the problem arises when I call the ajax function. In fact, excluding the ajax call, everything is ok. 
But I need the ajax call to get the unit price of the selected product.
I have triggered the CellSave event because I need to calculate the total price of the row every time I change Equipment or quantity.
But I can't understant how to solve the problem...Thanks

CLAUDIO RICCARDI
Replied On April 5, 2017 02:23 AM

Hi,after some other tests, I have found that the problem is related to the API method setCellValue.In fact, if I exclude the lines of code where setCellValue is called, the problem disappears.I'm using setCellValue because the grid is in Batch Edit Mode.Is there a workaround for this?Thanks.Claudio

Jayaprakash Kamaraj [Syncfusion]
Replied On April 5, 2017 07:28 AM

Hi claudio, 
 
We have analysed your requirement and found that you have used setCellValue in added record and also primaryKey value is zero for all the added rows. This is the cause of issue. Because we have performed editing operation based on primaryKey(unique) value. So, to overcome this problem we suggest you to use below work around. In this work around we have used BeforeBatchAdd, BeforeBatchSave and ActionComplete events of ejGrid to set auto increment value in primary Key column. Initially we need to set window variable as 1 and then we need to set that value in ags.defaultData.orderID in BeforeBatchAdd event and also need to increment window variable value. Please refer to the below help document and code example.  
 
 
@(Html.EJ().Grid<object>("Grid") 
                .Datasource(d => d.Json((IEnumerable<object>)ViewBag.data).BatchURL("/Home/BatchUpdate").Adaptor(AdaptorType.RemoteSaveAdaptor)) 
            .AllowPaging() 
            .. 
 
         
            }).ClientSideEvents(eve=>eve.CellSave("cellSave").ActionComplete("actioncomplete").BeforeBatchSave("beforebatchsave").BeforeBatchAdd("beforebatchadd")) 
) 
 
 
<script type="text/javascript"> 
    window.value = 1; 
.. 
    function beforebatchadd(args) { 
         var len = this.model.dataSource.dataSource.json.length; 
         var value = this.model.dataSource.dataSource.json[len - 1].OrderID; 
        args.defaultData.OrderID = value + window.value; 
        window.value = window.value + 1; 
    } 
</script> 
 
In beforBatchSave event we need to reset window variable as 1 and also we need to reset window variable as 1 when args.requestType as cancel in actionComplete event of ejGrid. Please refer to the below help documents, code example and sample.  
 
 
 
    function actioncomplete(args) { 
        if(args.requestType == "cancel") 
            window.value = 1; 
    } 
   function beforebatchsave(args) { 
        window.value = 1; 
    } 


Regards, 

Jayaprakash K. 
 


CLAUDIO RICCARDI
Replied On April 5, 2017 09:54 AM

Great!

It works.

Thank you very much.

Claudio

Jayaprakash Kamaraj [Syncfusion]
Replied On April 6, 2017 03:31 AM

Hi claudio, 
 
We are happy that the problem has been solved. 
 
Please get back to us if you need any further assistance.   
 
Regards, 
 
Jayaprakash K. 


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.

;