How would I update the grid data to the Web API when I Add / Update /Delete the grid data?

How would I update the grid data to the Web API when I Add / Update /Delete the grid data?

I am using the Dialog Template grid for my project. The data are locally updated when I Add / Update /Delete the grid data. I need to send the changed data to web API for Remote API Update.


This the whole code of the Grid.

index.js

ej.base.enableRipple(true);
$('#content').html('<img id="loader-img" alt="" src="loading.gif" width="30" height="30" align="center" />');

//var countryData = ej.data.DataUtil.distinct(orderData, 'deviceTypeID', true);
//var shipCityData = ej.data.DataUtil.distinct(orderData, 'ShipCity', true);
(function () {
    $.ajax({
        type: 'GET',
        contentType: "application/json",
        dataType: "json",
        url: "https://secsystemeventsapi.azurewebsites.net/api/Devices"
    }).
done(function (data) {
   
 
$('#content').html('<style ="visibility:hidden;"></style>');
        window.gridData = data;--------------------------------------------->I need this high-lighted function also .So kindly help me with this solution
        var index = 0;
        while (index < window.gridData.length)
        {gridData
            window.gridData[index].deviceID = window.gridData[index].deviceID.toString();
            window.gridData[index].deviceTypeID = window.gridData[index].deviceTypeID.toString();
            window.gridData[index].fwid = window.gridData[index].fwid.toString();
            index++;
        }
        grid.dataSource = window.gridData;

    });
})(); 
var grid = new ej.grids.Grid({
dataSource: window.gridData,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Dialog', template: '#dialogtemplate' },
toolbar: ['Add', 'Edit', 'Delete'],
columns: [
{
field: 'deviceID', isPrimaryKey: true, headerText: 'Device ID', textAlign: 'Center',
validationRules: { required: true, number: true }, width: 100, defaultValue: ''
},
{
field: 'deviceTypeID', headerText: 'Device Type ID', textAlign: 'Center',
validationRules: { required: true, number: true }, editType: 'dropdownedit', width: 100, defaultValue: ''
},
{
field: 'serialNO', headerText: 'Serial No',
validationRules: { required: true }, textAlign: 'Center', width: 100, defaultValue: ''
},
{
field: 'version', headerText: 'Version', textAlign: 'Center',
width: 100, defaultValue: ''},
{
field: 'brandName', headerText: 'Brand Name', textAlign: 'Center',
width: 100, defaultValue: ''
},
{
field: 'fwid', headerText: 'FWID', textAlign: 'Center', width: 100, defaultValue: ''
}
],



actionComplete: function(args) {
if ((args.requestType === 'beginEdit' || args.requestType === 'add')) {
var data = args.rowData;
var countryData =[{name:'Gateway',id:'1'},
{name:'Accelometer',id:'2'},
{name:'PanicButton',id:'3'},
{name:'Motion',id:'4'},
{name:'Smoke',id:'5'},
{name:'GlassBreak',id:'6'},
{name:'DoorContact',id:'7'}];

                // Convert Widget for the ShipCountry field
                new ej.dropdowns.DropDownList({value: data.deviceTypeID, popupHeight: '300px', floatLabelType: 'Always',
                 dataSource: countryData, fields: {text: 'name', value: 'id'}, placeholder: 'Device Type ID'},
                 args.form.elements.namedItem('deviceTypeID'));

                if (ej.base.Browser.isDevice) {
                 args.dialog.height = window.innerHeight - 90 + 'px';
                 args.dialog.dataBind();
                }

                // Set initail Focus
                if (args.requestType === 'beginEdit') {
                 args.form.elements.namedItem('serialNO').focus();
                } else {
                 args.form.elements.namedItem('deviceID').focus();
                }
            }
        }
    });
grid.appendTo('#Grid');





 Thank You.

3 Replies

SK Sujith Kumar Rajkumar Syncfusion Team May 4, 2020 10:48 AM UTC

Hi Arshad, 

Greetings from Syncfusion support. 

Since you are using data returned from the Web API and binding it locally to the Grid, we suggest you to use the Web API adaptor to bind remote data to the Grid. On using this approach the data returned from the Web API is directly bound to the Grid and since the CRUD operations are performed in the server-side, it will be updated both in the server data and Grid. 

More details on the Web API adaptor can be found in the below help documentation link, 


We have also prepared a sample based on this for your reference. You can download it from the following link, 


Please get back to us if you require any further assistance. 

Regards, 
Sujith R 



AR Arshad May 5, 2020 12:59 PM UTC

I had changed as per your guideline but it's not working.cant update/add/create.

index.js

ej.base.enableRipple(true);
var hostUrl = 'https://secsystemeventsapi.azurewebsites.net/'; 
var data = new ej.data.DataManager({ 
url: hostUrl + 'api/Devices', 
adaptor: new ej.data.WebApiAdaptor(), 
offline:true  
});


var countryData = [{name : 'Gateway',id : 1},
{name : 'Accelometer',id : 2},
{name : 'PanicButton',id : 3},
{name : 'Motion',id : 4},
{name : 'Smoke',id : 5},
{name : 'GlassBreak',id : 6},
{name : 'DoorContact',id : 7}]


var grid = new ej.grids.Grid({
dataSource: data,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Dialog', template: '#dialogtemplate' },
toolbar: ['Add', 'Edit', 'Delete'],
columns: [
{
field: 'deviceID', headerText: 'Device ID', textAlign: 'Center',
width: 100, defaultValue: '', isPrimaryKey: true
},
{
field: 'deviceTypeID', headerText: 'Device Type ID', textAlign: 'Center',
validationRules: { required: true }, editType: 'dropdownedit', width: 100, defaultValue: '',foreignKeyValue: 'name', foreignKeyField: 'id',dataSource:countryData
},
{
field: 'serialNO', headerText: 'Serial No',
validationRules: { required: true }, textAlign: 'Center', width: 100, defaultValue: ''
},
{
field: 'version', headerText: 'Version',validationRules: { required: true }, textAlign: 'Center',
width: 100, defaultValue: ''},
{
field: 'brandName', headerText: 'Brand Name',validationRules: { required: true }, textAlign: 'Center',
width: 100, defaultValue: ''
},
{
field: 'fwid', headerText: 'FWID', textAlign: 'Center', width: 100, defaultValue: ''
}
],



actionComplete: function(args) {
if ((args.requestType === 'beginEdit' || args.requestType === 'add')) {
var data = args.rowData;


                // Convert Widget for the ShipCountry field
                new ej.dropdowns.DropDownList({value: data.deviceTypeID, popupHeight: '300px', floatLabelType: 'Always',
                dataSource: countryData, fields: {text: 'name', value: 'id'}, placeholder: 'Device Type ID'},
                args.form.elements.namedItem('deviceTypeID'));

                if (ej.base.Browser.isDevice) {
                args.dialog.height = window.innerHeight - 90 + 'px';
                args.dialog.dataBind();
                }

                // Set initail Focus
                if (args.requestType === 'beginEdit') {
                args.form.elements.namedItem('serialNO').focus();
                } else {
                args.form.elements.namedItem('deviceID').focus();
                }

            }

            
        }
    });



grid.appendTo('#Grid');



SK Sujith Kumar Rajkumar Syncfusion Team May 6, 2020 10:52 AM UTC

Hi Arshad, 
 
By default, when you offline mode is set as true in data manager, it gets all the remote data at initialization and performs all the grid action in the client side which is the default behaviorIf you need the data to be updated on server-side then you need to set offline mode of the data manager as false. Then you need to update the data received in the controller for each CRUD operation to your server and return the value. This is demonstrated on the basis of updating local data in the below code snippet, 
 
Controller part 
// Data request to fetch display data will call this method 
// GET: api/Orders 
[HttpGet] 
public object Get() 
        { 
            var data = OrdersDetails.GetAllRecords().ToList(); 
            var query = HttpContext.Request.Query; 
            StringValues skip; 
            StringValues take; 
            query.TryGetValue("$skip", out skip); 
            query.TryGetValue("$top", out take); 
            return new { Items = data.Skip(Convert.ToInt32(skip)).Take(Convert.ToInt32(take)), Count = data.Count() }; 
        } 
 
// GET: api/Orders/5 
[HttpGet("{id}", Name = "Get")] 
public string Get(int id) 
        { 
            return "value"; 
        } 
 
// Data request when adding a new data will call HTTPPost method 
// POST: api/Orders 
[HttpPost] 
public object Post([FromBody]OrdersDetails value) 
        { 
            // Here you need to insert the data to your server and return the added value 
            OrdersDetails.GetAllRecords().Insert(0, value); 
            return value; 
        } 
 
// Data request when editing a data will call HTTPPut method 
// PUT: api/Orders/5 
[HttpPut] 
public object Put(int id, [FromBody]OrdersDetails value) 
        { 
            // Here you need to update the data to your server and return the updated value 
            var data = OrdersDetails.GetAllRecords().Where(or => or.OrderID == value.OrderID).FirstOrDefault(); 
            if (data != null) 
            { 
                var ord = value; 
                OrdersDetails val = OrdersDetails.GetAllRecords().Where(or => or.OrderID == ord.OrderID).FirstOrDefault(); 
                val.OrderID = ord.OrderID; 
                val.CustomerID = ord.CustomerID; 
                val.ShipCountry = ord.ShipCountry; 
                val.ShipCity = ord.ShipCity; 
            } 
            return value; 
        } 
 
// Data request when deleting a data will call HTTPDelete method 
// DELETE: api/ApiWithActions/5 
[HttpDelete("{id:int}")] 
[Route("Orders/{id:int}")] 
public void Delete(int id) 
        { 
            // Here you need to remove the data from your server 
            var data = OrdersDetails.GetAllRecords().Where(or => or.OrderID == id).FirstOrDefault(); 
            OrdersDetails.GetAllRecords().Remove(data); 
        } 
 
You can check the above process flow in the sample we provided in our last update. 
 
Let us know if you have any concerns. 
 
Regards, 
Sujith R 


Loader.
Up arrow icon