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. Image for the cookie policy date

Save grid data together on external save button

Hello,

I am using syncfusion grid with inline edit option and URl adapter. Currently on insert or update ,the grid is going back to controller and storing a single row. But i would like to first add the rows and then store all the newly added rows to database on external button click event. The user can add new rows or update the existing one but the data should be saved together in database on external button event.
the is how i have initialized the grid- 



  @(Html.EJ().Grid<GradeEntitlementModel>("FlatGrid")
                    .Datasource(ds => ds.URL(Url.Action("GrdEntlDataSource", "CRUD", null, Request.Url.Scheme)).InsertURL(Url.Action("GrdEntlInsert", "CRUD", null, Request.Url.Scheme)).UpdateURL(Url.Action("GrdEntlUpdate", "CRUD", null, Request.Url.Scheme)).RemoveURL(Url.Action("GrdEntlDelete", "CRUD", null, Request.Url.Scheme)).Adaptor(AdaptorType.UrlAdaptor))
                    .EnableAltRow()
                    .AllowFiltering()
                    .SelectedRowIndex(0)
                    .IsResponsive()
                    .AllowSorting()
                    .GridLines(GridLines.Horizontal)
                    .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); })
                    .PageSettings(page =>
                    {
                        page.PageSize(5);
                    })
                    .AllowTextWrap()
                    .AllowResizeToFit()
                    .EnableHeaderHover()
                    .FilterSettings(filter => { filter.FilterType(FilterType.Excel); })
                    .AllowPaging()
                    .ClientSideEvents(eve =>
                    {
                        eve.ActionComplete("complete");
                        eve.ActionFailure("failure");

                        eve.RecordClick("recordClick");
                        eve.RecordDoubleClick("recordDoubleClick");
                        eve.ContextOpen("contextopen");
                        eve.ContextClick("contextclick");
                        eve.ActionBegin("beginAction");
                    })
                    .Columns(col =>
                    {
                        col.Field(p => p.entlId).HeaderText("id").IsPrimaryKey(true).Visible(false).TextAlign(TextAlign.Left).ValidationRules(v => v.AddRule("required", true).AddRule("number", true)).Width(70).Add();

                        col.Field(p => p.entlCode).HeaderText("Entl.Code").TextAlign(TextAlign.Left).ValidationRules(v => v.AddRule("required", true).AddRule("number", true)).Width(70).Add();
                        col.Field(p => p.entlDescription).HeaderText("Description").TextAlign(TextAlign.Left).ValidationRules(v => v.AddRule("required", true).AddRule("number", true)).Width(70).Add();

                        col.Field(p => p.remarks).HeaderText("Remarks").TextAlign(TextAlign.Left).Add();



                    })
                )

As you can see i have used the URL adapter to perform the crud operation and its working fine. But as i mentioned, i want to pass the grid data to controller on external button click event. I found one code in web where the data is passed in json in string but i am not able to convert that json string to list of object. 
this is the code i found on web-

 $("#save").click(function (){
            var gridmodel = $("#FlatGrid").ejGrid("model");
            var data = JSON.stringify(gridmodel.dataSource);

            $.ajax({
                url:'@Url.Action("EduDeptInsert", "CRUD")',
                type:'post',
                data:{value: data},

                success:function(data){

                }

            });
            
        });

Please guide me how to achieve this with URL adapter. if its not possible with this then which adapter should i use to get this result.

Regards ,

Sachin 

3 Replies

SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team January 6, 2017 09:20 AM UTC

Hi Sachin, 
 
We can achieve your requirement “To save multiple records in Single POST” using the Batch Editing Mode feature of the Grid. Refer to the following code example and Help Documents for Batch Editing Mode. 
 
@(Html.EJ().Grid<object>("FlatGrid") 
                    .EditSettings(edit => 
                    { 
                        edit.AllowAdding() 
                            .AllowDeleting() 
                            .AllowEditing() 
                            .EditMode(EditMode.Batch); 
                    }) 
 
) 
 
 
The updated changes can be posted to the server end using the batchSave method (recommended only for the Batch Editing) of the Grid. Refer to the following API Reference Section.  
 
  
In your case, on clicking the button, multiple records have to be updated to the server. We have already discussed about this in the following KB using batchSave method button click event.  
 
 
Refer to the following code example. 
 
<input type="button" value="Save" onclick="SaveHandler()" /> 
 
@(Html.EJ().Grid<object>("FlatGrid") 
                    .EditSettings(edit => 
                    { 
                        edit.AllowAdding() 
                            .AllowDeleting() 
                            .AllowEditing() 
                            .EditMode(EditMode.Batch); 
                    }) 
 
) 
 
<script type="text/javascript"> 
    function SaveHandler() { 
        var obj = $("#FlatGrid").ejGrid("instance") 
        obj.batchSave() 
    } 
</script> 
 
We cannot use the InsertURL, RemoveURL and UpdateURL methods of the DataManager for the Batch Editing. However, you can use the BatchURL method of the DataManager to update the BatchChanges to the Server. Refer to the following code example and Help Document. 
 
 
<input type="button" value="Save" onclick="SaveHandler()" /> 
 
@(Html.EJ().Grid<object>("FlatGrid") 
                    .Datasource(ds => 
                        ds.URL(Url.Action("GrdEntlDataSource", "CRUD", null, Request.Url.Scheme)) 
                        .BatchURL(Url.Action("GrdBatchUpdate", "CRUD", null, Request.Url.Scheme)) 
                        .Adaptor(AdaptorType.UrlAdaptor)) 
                    .EditSettings(edit => 
                    { 
                        edit.AllowAdding() 
                            .AllowDeleting() 
                            .AllowEditing() 
                            .EditMode(EditMode.Batch); 
                    }) 
 
) 
 
<script type="text/javascript"> 
    function SaveHandler() { 
        var obj = $("#FlatGrid").ejGrid("instance") 
        obj.batchSave() 
    } 
</script> 
 
        public ActionResult GrdBatchUpdate(string action, List<EditableOrder> added, List<EditableOrder> changed, List<EditableOrder> deleted, int? key) 
        { 
            //Save the batch changes in database 
        } 
 
 
We also have online demo on this Batch Editing and BatchURL. 
 
 
Regards, 
Seeni Sakthi Kumar S. 



SA sachin January 7, 2017 12:45 PM UTC

Hello Seeni,

Thanks for your advice, the batch edit mode has done the job for me. but i am stuck with other problem where i need to set batch cell value. When user clicks on cell to edit it , i am showing a popup model containing another syncfusion grid to let the user select values from the grid. In inline edit mode this functionality was working fine, i was able to get the selected value from the popup grid and assign that value to the selected grid cell by using the id of the cell (e.g. -  $("#" + this._id +"departmentCode").val("value") ) this method is not working with batch edit mode. Please help me how to get the selected value from a popup grid  and assign it to the main grid cell. this is my main grid 

   @(Html.EJ().Grid<EducationDepartmentModel>("FlatGrid")
            .Datasource(ds => ds.URL(Url.Action("EduDeptDataSource", "CRUD", null, Request.Url.Scheme)).BatchURL(Url.Action("EduDeptBatchUpdate", "CRUD", null, Request.Url.Scheme)).Adaptor(AdaptorType.UrlAdaptor))
            .EnableAltRow()
            .AllowFiltering()
            .SelectedRowIndex(0)
            .IsResponsive()
            .AllowSorting()
            .GridLines(GridLines.Horizontal)
            .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch); })
            .PageSettings(page =>
            {
                page.PageSize(5);
            })
            .AllowTextWrap()
            .AllowResizeToFit()
            .EnableHeaderHover()
            .FilterSettings(filter => { filter.FilterType(FilterType.Excel); })
            .AllowPaging()
            .ClientSideEvents(eve =>
            {
                eve.ActionComplete("complete");
                eve.ActionFailure("failure");

                eve.RecordClick("recordClick");
                eve.RecordDoubleClick("recordDoubleClick");
                eve.ContextOpen("contextopen");
                eve.ContextClick("contextclick");
                eve.ActionBegin("beginAction");          
                eve.BeforeBatchAdd("beforeBatchAdd");
                eve.CellEdit("cellEdit");
              

                

            })
            .Columns(col =>
            {
                col.Field(p => p.departmentId).HeaderText("Department ID").IsPrimaryKey(true).Visible(false).TextAlign(TextAlign.Left).Width(70).Add();
                col.Field(p => p.educationId).HeaderText("Department ID").Visible(false).TextAlign(TextAlign.Left).Width(70).Add();

                col.Field(p => p.departmentCode).HeaderText("Department Code").TextAlign(TextAlign.Left).ValidationRules(v => v.AddRule("required", true).AddRule("number", true)).Width(70).Add();
                col.Field(p => p.description).HeaderText("Description").Width(90).ValidationRules(v => v.AddRule("required", true).AddRule("maxlength", 40)).Add();
                col.Field(p => p.budgetAmount).HeaderText("Budget Amount").EditType(EditingType.Numeric).Format("{0:C}").NumericEditOptions(new EditorProperties() { DecimalPlaces = 2 }).ValidationRules(v => v.AddRule("range", "[0,1000]")).Add();

                col.Field(p => p.costIncurred).HeaderText("Cost Incurred").EditType(EditingType.Numeric).Format("{0:C}").NumericEditOptions(new EditorProperties() { DecimalPlaces = 2 }).ValidationRules(v => v.AddRule("range", "[0,1000]")).Add();



            })
                )


To open the popup dialog box , i am using this code -
 
function cellEdit(args){                  

            
            if(args.columnName == "description"){
                args.cancel = true;           


            }

            if(args.columnName == "departmentCode"){
                $("#helpDialog").ejDialog("open");

            }

        }

and this is my popup grid model -
 

@{Html.EJ().Dialog("helpDialog").Title("Cost Center Code").IsResponsive(true).ShowOnInit(false).ContentTemplate(@<div>
        <form id="form1">
            @(Html.EJ().Grid<DepartmentModel>("FlatGrid2").Datasource(ds => ds.Json((IEnumerable<object>)ViewBag.dataSource2))
                    .AllowSelection()
                    .AllowTextWrap()
                    .EnableHeaderHover()
                    .EnableAltRow()

                    .AllowPaging()
                    .ToolbarSettings(toolbar =>
                    {
                        toolbar.ShowToolbar().ToolbarItems(items =>
                        {
                            items.AddTool(ToolBarItems.Search);
                        });
                    })
                    .PageSettings(page =>
                    {
                        page.PageSize(10);
                    })
                    .ClientSideEvents(eve =>
                    {

                        eve.RecordDoubleClick("select");


                    })
                    .Columns(col =>
                    {
                        col.Field(p => p.departmentCode).HeaderText("Department Code").IsPrimaryKey(true).Width(50).TextAlign(TextAlign.Left).Add();

                        col.Field(p => p.description).HeaderText("Department Description").TextAlign(TextAlign.Left).Width(90).Add();

                    })
            )


        </form>
    </div>).EnableModal(true).EnableResize(false).ClientSideEvents(evt => evt.Close("onDialogClose")).IsResponsive(true).Render();}

as you can see , i have added recordDoubleClick event to get the selected row value-

function select(args) {
            var result = this.getSelectedRecords();
            var costCode = result[0].departmentCode;
            var costDesc = result[0].description;

            $("#helpDialog").ejDialog("close");

            alert(args.value);
            var gridInstance = $("#FlatGrid").ejGrid("instance");

            var index = gridInstance.selectedRowsIndexes;        



            gridInstance.setCellText(index, "departmentCode", costCode);
            gridInstance.setCellText(index, "description", costDesc);


        }

when i use this code ,instead of setting the selected value to the cell , it creates a new textbox and set the selected value to it . Please guide me how to achieve this.

Regards, 
Sachin 





SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team January 9, 2017 12:48 PM UTC

Hi Sachin, 
 
We are able to reproduce the problem at our end. The setCellText will not work with the Batch Edit Mode. So we suggest to use the setCellValue method of the Grid which has been recommended only for the Batch Edit mode of the Grid. Refer to the following code example and Help Document. 
 
    function select(args) { 
        var result = this.getSelectedRecords(); 
        var CustomerID = result[0].CustomerID; 
        var gridInstance = $("#FlatGrid").ejGrid("instance"); 
        var index = gridInstance.selectedRowsIndexes; 
        gridInstance.setCellValue(index, "CustomerID", CustomerID); 
        $("#helpDialog").ejDialog("close"); 
    } 
 
 
We have also prepared a sample with your requirement that can be downloaded from the following location. 
 
 
Regards, 
Seeni Sakthi Kumar S. 


Loader.
Live Chat Icon For mobile
Up arrow icon