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

Data from collection not physically saved in database

Dear Sirs,

I have written an very simple HTML client application using ejgrid to test functionality and I have a couple of questions:

1.  Everything works ok with the exception that data is not physically written to the database. I understand that what the grid displays is json data and perhaps not tied to the visual collection. My question is how to allow the grid data to be physically saved to the database. I need to perform, add, delete and edit functions. This is my code:

/// <reference path="~/GeneratedArtifacts/viewModel.js" />
myapp.TestSyncFusion.TestSync_render = function (element, contentItem) {
    var itemTemplate = $("<div></div>").attr('id', 'TestSync')
    // Append the div element to screen
    itemTemplate.appendTo($(element));
    contentItem.value.oncollectionchange = function () {
        if (itemTemplate.hasClass('e-grid')) {
            itemTemplate.ejGrid('destroy');
        }
       
        var first = contentItem.children[0], fieldname=[];
        for (i = 0; i < first.children.length; i++) {
            fieldname[i] = { field: first.children[i].valueModel.name };
        }
        fieldname[0].isPrimaryKey = true;
        //Rendering the Grid Control
        itemTemplate.ejGrid(
            {
                dataSource: contentItem.value.data,
                allowPaging: true,
                pageSettings: { pageCount: 3 },
                isResponsive: true,
                allowSorting: true,
                enableResponsiveRow: true,
                allowSelection: true,
                allowSorting: true,
                allowMultiSorting: true,
                allowResizing: true,
                allowGrouping: true,
                allowReordering: true,
                enableRowHover: true,
                allowTextWrap: true,
                allowSearching: true,
                locale: "es-ES",
                // Set up edit settings
                editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true},
                // Set up toolbar
                toolbarSettings: {
                    showToolbar: true,
                    toolbarItems: [ej.Grid.ToolBarItems.Search, ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Edit, ej.Grid.ToolBarItems.Delete, ej.Grid.ToolBarItems.Update, ej.Grid.ToolBarItems.Cancel, ej.Grid.ToolBarItems.ExcelExport, ej.Grid.ToolBarItems.WordExport, ej.Grid.ToolBarItems.PdfExport]
                },
                // Setup Columns and their display attributes
                columns: [
                          { field: "Nombre", headerText: "Nombre(s)", textAlign: ej.TextAlign.Left, width: 200 },
                          { field: "Apellido", headerText: 'Apellido(s)', textAlign: ej.TextAlign.Left, width: 150 },
                          { field: "Fecha", headerText: 'Fecha', width: 90, format: "{0:MM/dd/yyyy}", editType: ej.Grid.EditingType.DatePicker, editParams: { showPopupButton: true } }
                     ],
              
                // Process grid action (save, delete etc....)
                actionBegin: function (args)
                {
                    switch (args.requestType)
                    {
                        case "delete":
                            contentItem.value.selectedItem = this.getSelectedRecords()[0];
                            contentItem.value.deleteSelected(); //delete the records in grid
                            myapp.applyChanges();
                            break;
                        case "save":
                             myapp.applyChanges();
                            break;
                    }  
                },
                // Handdle Export toolbar actions
                toolbarClick: function (e) {
                    this.exportGrid = this["export"];
                    if (e.itemName == "Exportar a Excel") {
                        this.exportGrid("../Exports/ExportSyncFusion/ExcelExport")
                        e.cancel = true;
                    }
                    else if (e.itemName == "Exportar a Word") {
                        this.exportGrid("../Exports/ExportSyncFusion/WordExport")
                        e.cancel = true;
                    }
                    else if (e.itemName == "Exportar a Pdf") {
                        this.exportGrid("../Exports/ExportSyncFusion/PdfExport")
                        e.cancel = true;
                    }
                },
                  
            });
    }
}

2. Would it be better to create add/view independent screens to allow the above instead of using the grid for such operations?.

3. The exporting functions need a webapi, the one I am using is a standard one based on code I have seen in your examples. Apparently I need to create webapi's for each table in my database, is there a way to create just one single webapi that can use the entity name to do it's exporting operations (for both the grid data as well as individual record selected)? and if so could you provide me with an example?.

Thank you very much for any help provided and kind regards,

Alberto Rojas


6 Replies

IR Isuriya Rajan Syncfusion Team September 28, 2015 02:57 PM UTC

Hi Alberto,
Currently we are validating your requirement and we will update the response on 29th September 2015.
Regards,
Isuriya R


IR Isuriya Rajan Syncfusion Team September 29, 2015 02:38 PM UTC

Hi Alberto, 


Query #1: My question is how to allow the grid data to be physically saved to the database. I need to perform, add, delete and edit functions. This is my code:


In the previous version, we passed Grid dataSource using the dataManager which made some issue with saving dataSource. But in the latest version issues have been fixed and you can save the dataSource.

Query #2: Would it be better to create add/view independent screens to allow the above instead of using the grid for such operations?

We have achieved the requirement using the toolbarClick event. You can also perform Edit, Add operations in an individual screen. Please refer to the below code example to achieve Add, Edit and Delete operations.

toolbarClick: function (args) {

                    switch (args.itemName) {

                        case "Add": //Adding the record

                            args.cancel = true;

                            myapp.showScreen("AddEditTable1Item", null, {

                                beforeShown: function (addScreen) {

                                    var ord = new myapp.Table1Item();

                                    addScreen.Table1Item = ord;

                                }

                            });

                            break;

                        case "Edit": //Editing the record

                            if (!($.isEmptyObject(selectedData))) {

                                args.cancel = true;

                                myapp.showScreen("AddEditTable1Item", [selectedData])

                            }

                            break;

                        

                                   }                    
                }



Query #3: The exporting functions need a webapi, the one I am using is a standard one based on code I have seen in your examples. Apparently I need to create webapi’ s for each table in my database, is there a way to create just one single webapi that can use the entity name to do it's exporting operations (for both the grid data as well as individual record selected)? And if so could you provide me with an example?

This requirement is achieved using export method in Grid. You can use single webapi for multigrid exporting. 


toolbarClick: function (args) {

            switch (args.itemName) {


case "Excel Export": // Grid exporting 

                                       this.model["exportdata"] =this.model.dataSource.map(function (obj) {

                                           return {

                                                OrderID: obj.OrderID,

                                                EmployeeID: obj.EmployeeID,

                                                City: obj.City,

                                               Freight: obj.Freight

                                            };

                                        });

                                       this.export('../api/Values/ExcelExport')

                                        e.cancel = true;


                  }
                    }


For individual selected record exporting, we have passed the selected records to the export function.



// Cilent side

toolbarClick: function (args) {

            switch (args.itemName) {


case "Excel Export": // Grid exporting 

           this.model["exportdata"] = this.getSelectedRecords()


                  }

                    }


public void ExportToExcel(string GridModel)

        {

            ExcelExport exp = new ExcelExport();// Pass selected records alone for exporting 

            exp.Export(obj, this.ExportData, "Export.xlsx", ExcelVersion.Excel2010,false, false, "flat-saffron");
        }


private GridProperties ConvertGridObject(string gridProperty)

        {

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty,typeof(IEnumerable));

            GridProperties gridProp = new GridProperties();

            foreach (KeyValuePair<string, object> ds in div)

            {

                if (ds.Key == "selectedRecords")

                {();// Serialize the selected records 


                    string serialize = serializer.Serialize(ds.Value);

                    this.ExportData = (List<OrdersView>)serializer.Deserialize(serialize,typeof(List<OrdersView>));

                    continue;

                }

                var property = gridProp.GetType().GetProperty(ds.Key,BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);

                if (property != null)

                {

                    Type type = property.PropertyType;

                    string serialize = serializer.Serialize(ds.Value);

                    object value = serializer.Deserialize(serialize, type);

                    property.SetValue(gridProp, value, null);

                }

            }

            return gridProp;
        }



We have created a sample and attached for your reference,


http://www.syncfusion.com/downloads/support/forum/120570/ze/Grid-Exporting379737180

Regards,
Isuriya R




AR Alberto Rojas September 30, 2015 06:58 PM UTC

Isuriya,

Thank you very much for your answer.

I have tested the sample application you sent and it works with the following exceptions:

1. If I test on an empty table I get:  "DataSource must not be empty at initial load since columns are generated from dataSource in AutoGenerate Column Grid". Is there a work around this issue? and if not then the use of the ejgrid itself to add records is impractical because in any case an add/edit screen needs to be created to at least load one record.

2. If I click on the edit button without selecting a row I get an error: 0x800a1391 - JavaScript runtime error: 'selectedData' is undefined. This does not happen if I click the trash button, I get No records selected for deletion. I tried the following code:

case "Edit":

if (($.isEmptyObject(selectedData)) || (selectedData === undefined)) {

msls.showMessageBox("Display message")

}

But, did not get anywhere, the same error occurs.

3. When I select a row (by highlighting it) and try to export it, VS 2013 crashes and is unresponsive. Checking the error generated and I get SCRIPT5034: Unhandled exception at line 10, column 1874200 in web.all.min.js and I have to end the task.


4. I think my question #3 was misunderstood. My system has over 300 tables and the question was geared towards optimizing the webapi in ONE SINGLE file instead of having to create 300 individual  WebApi files. Do I have to create individual WebApi's for each table?.

I appreaciate your answers and kind regards,

Alberto Rojas


BM Balaji Marimuthu Syncfusion Team October 2, 2015 11:35 AM UTC

Hi Alberto,

We regret for the inconvenience.

Query #1: If I test on an empty table I get:  "DataSource must not be empty at initial load since columns are generated from dataSource in AutoGenerate Column Grid". Is there a work around this issue? and if not then the use of the ejgrid itself to add records is impractical because in any case an add/edit screen needs to be created to at least load one record.

If you are rendering the Grid with AutoGenerated columns, you should specify the DataSource (must not be empty). Based on the DataSource only, columns will be generated. So we suggest you to render the Grid by specifying either DataSource (Not null) or Columns.

Once columns initialized you can add the records using the addRecords method.

 

Query #2:  If I click on the edit button without selecting a row I get an error: 0x800a1391 - JavaScript runtime error: 'selectedData' is undefined. This does not happen if I click the trash button, I get No records selected for deletion. I tried the following code:

Initially we do not define the selectedData value, that is the cause of this issue. By declaring the selectedData as null we can solve this issue. The rowSelect event gets the selected records in grid. 
 

var selectedData = null;

case "Edit":

                            if (selectedData!= null && !($.isPlainObject(selectedData))) {

                                args.cancel = true;

                                myapp.showScreen("AddEditTable1Item", [selectedData])

                            }
                            break;



Query:#3 When I select a row (by highlighting it) and try to export it, VS 2013 crashes and is unresponsive. Checking the error generated and I get SCRIPT5034: Unhandled exception at line 10, column 1874200 in web.all.min.js and I have to end the task.

If you want to export the selected records only, we suggest you to use the below code example and push the selectedRecords property in the ignoreOnExport method. 


Please refer to the Sample in the following link:
Sample:
Exporting-lightswitch

//push the selectedRecords in ignoreonexport
    ej.Grid.prototype.ignoreOnExport.push("selectedRecords");

toolbarClick: function (args) {

        

                       . . .


                        case "Excel Export":

                            args.cancel = true;

                            if (this.selectedRowsIndexes.length > 0)  //export selected records

                                this.model["exportdata"] = this.getSelectedRecords().map(function (obj) {

                                    // get selected records by using this.getSelectedRecords()

                                    return {

                                        OrderID: obj.OrderID,

                                        EmployeeID: obj.EmployeeID,

                                        City: obj.City,

                                        Freight: obj.Freight

                                    };

                                });

                            else

                                this.model["exportdata"] = this.model.dataSource.map(function (obj) { //export entire datasource

                                    return {

                                        OrderID: obj.OrderID,

                                        EmployeeID: obj.EmployeeID,

                                        City: obj.City,

                                        Freight: obj.Freight

                                    };

                                });


                            this.export('../api/Values/ExcelExport')

                    }

                }
            });



Query:#4 . I think my question #3 was misunderstood. My system has over 300 tables and the question was geared towards optimizing the webapi in ONE SINGLE file instead of having to create 300 individual  WebApi files. Do I have to create individual WebApi's for each table?.

No, you can use one single WebApi to export 300 tables. Instead of binding the data in WebApi, you can pass the record (this.model[“exportdata”]) from client to Server Side and export it. Please refer to the attached sample.


[System.Web.Http.ActionName("ExcelExport")]

        [AcceptVerbs("POST")]

        public void ExcelExport()

        {

            string gridModel = HttpContext.Current.Request.Params["GridModel"];

            GridProperties gridProperty = ConvertGridObject(gridModel);

            ExcelExport exp = new ExcelExport();


            using (ServerApplicationContext context = ServerApplicationContext.CreateContext())

            {

            exp.Export(gridProperty, (IEnumerable)gridProperty.DataSource, "Export.xlsx", ExcelVersion.Excel2010);

            }

        }

        private GridProperties ConvertGridObject(string gridProperty)

        {

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty, typeof(IEnumerable));

            IEnumerable<Order> data = null;

            GridProperties gridProp = new GridProperties();

            foreach (KeyValuePair<string, object> ds in div)

            {

                var property = gridProp.GetType().GetProperty(ds.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);

                if (property != null)

                {

                    Type type = property.PropertyType;

                    string serialize = serializer.Serialize(ds.Value);

                    object value = serializer.Deserialize(serialize, type);                  

                    property.SetValue(gridProp, value, null);

                }

               

                if (ds.Key == "exportdata" )

                {

                    string serialize = serializer.Serialize(ds.Value);

                    data = serializer.Deserialize<Order[]>(serialize).Cast<Order>().ToList();

                }

            }

            gridProp.DataSource = data;

            return gridProp;
        }




Regards,
Balaji Marimuthu




AR Alberto Rojas October 2, 2015 02:31 PM UTC

Balaji,

Thank you very much for your answer. I will check your comments and post.

Kind Regards,

Alberto Rojas


IR Isuriya Rajan Syncfusion Team October 5, 2015 09:29 AM UTC

 Hi Alberto,

Please check and get back to us for further assistance.

Regards,

Isuriya R


Loader.
Live Chat Icon For mobile
Up arrow icon