Search results

Data Binding

The Grid uses DataManager, which supports both RESTful JSON data services binding and local JavaScript object array binding. The DataSource property can be assigned either with the instance of DataManager or JavaScript object array collection. It supports the following kinds of data binding method:

  • List binding
  • DataTable binding
  • Remote data

List binding

To bind list binding to the grid, you can assign a JavaScript object array to the DataSource property. The list data source can also be provided as an instance of the DataManager.

tagHelper
local.cs
<ejs-grid id="Grid" dataSource=@ViewBag.DataSource allowPaging="true">
            
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer Name" width="150"></e-grid-column>
        <e-grid-column field="OrderDate" headerText=" Order Date" textAlign="Right" format="yMd" width="130"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="ShippedDate" headerText="Shipped Date" textAlign="Right" format="yMd" width="140"></e-grid-column>                
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
    </e-grid-columns>

 </ejs-grid>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

By default, DataManager uses JsonAdaptor for list data-binding.

Remote data

To bind remote data to grid component, assign service data as an instance of DataManager to the DataSource property. To interact with remote data source, provide the endpoint url.

tagHelper
remotedata.cs
<ejs-grid id="Grid">
    <e-datamanager url="http://services.odata.org/V4/Northwind/Northwind.svc/Orders/?$top=7" adaptor="ODataV4Adaptor" crossdomain="true"></e-datamanager>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
       return view(); 
}

By default, DataManager uses ODataAdaptor for remote data-binding.

Binding with OData services

OData is a standardized protocol for creating and consuming data. You can retrieve data from OData service using the DataManager. Refer to the following code example for remote Data binding using OData service.

tagHelper
odata.cs
<ejs-grid id="Grid">
    <e-datamanager url="http://js.syncfusion.com/ejServices/Wcf/Northwind.svc/Orders/?$top=7" adaptor="ODataAdaptor" crossdomain="true"></e-datamanager>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
    return View();
}

Binding with OData v4 services

The ODataV4 is an improved version of OData protocols, and the DataManager can also retrieve and consume OData v4 services. For more details on OData v4 services, refer to the odata documentation. To bind OData v4 service, use the ODataV4Adaptor.

tagHelper
odataV4.cs
<ejs-grid id="Grid">
    <e-datamanager url="http://services.odata.org/V4/Northwind/Northwind.svc/Orders/?$top=7" adaptor="ODataV4Adaptor" crossdomain="true"></e-datamanager>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
    
    return View();
}

Web API

You can use WebApiAdaptor to bind grid with Web API created using OData endpoint.

tagHelper
webapi.cs
<ejs-grid id="Grid">
    <e-datamanager url="/api/Orders" adaptor="WebApiAdaptor" crossdomain="true"></e-datamanager>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
 </ejs-grid>
public IActionResult Index()
{
    
    return View();
}

The response object should contain properties, Items and Count, whose values are a collection of entities and total count of the entities, respectively.

The sample response object should look like this:

{
    Items: [{..}, {..}, {..}, ...],
    Count: 830
}

Remote Save Adaptor

You may need to perform all Grid Actions in client-side except the CRUD operations, that should be interacted with server-side to persist data. It can be achieved in Grid by using RemoteSaveAdaptor.

Datasource must be set to json property and set RemoteSaveAdaptor to the adaptor property. CRUD operations can be mapped to server-side using updateUrl, insertUrl, removeUrl, batchUrl, crudUrl properties.

You can use the following code example to use RemoteSaveAdaptor in Grid.

tagHelper
remotesaveadaptor.cs
<ejs-grid id="Grid" toolbar="@(new List<string>() { "Add","Delete","Update", "Cancel" })">
    <e-data-manager json ="@ViewBag.datasource" adaptor="RemoteSaveAdaptor" insertUrl="/Home/Insert" updateUrl="/Home/Update" removeUrl="/Home/Delete" ></e-data-manager>
    <e-grid-editSettings allowDeleting="true" allowEditing="true" allowAdding="true"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number"  textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
 </ejs-grid>
public ActionResult Index()
    {
       var data = OrderRepository.GetAllRecords();
       ViewBag.dataSource = data;
       return View();
    }
    public ActionResult Update(EditableOrder value)
    {
       OrderRepository.Update(value);
       var data = OrderRepository.GetAllRecords();
       return Json(data, JsonRequestBehavior.AllowGet);
    }
    public ActionResult Insert(EditableOrder value)
    {
       OrderRepository.Add(value);
       var data = OrderRepository.GetAllRecords();
       return Json(data, JsonRequestBehavior.AllowGet);
    }
    public ActionResult Delete(int key)
    {
       OrderRepository.Delete(key);
       var data = OrderRepository.GetAllRecords();
       return Json(data, JsonRequestBehavior.AllowGet);
    }

WebMethod

The WebMethodAdaptor is used to bind data source from remote services and code behind methods. It can be enabled in Grid using Adaptor property of DataManager as WebMethodAdaptor.

For every operations, an AJAX post will be send to the specified data service.

tagHelper
webapi.cs
<ejs-grid id="Grid">
    <e-datamanager url="Default.aspx/DataSource" adaptor="WebMethodAdaptor" crossdomain="true"></e-datamanager>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
 </ejs-grid>
public IActionResult Index()
{
    
    return View();
}

WebMethodAdaptor expects JSON response from the server and the response object should contain properties result and count whose values are collection of entities and total count of the entities respectively.

The sample response object should look like below.

{
    result: [{..}, {..}, {..}, ...],
    count: 830
}

The controller method’s data parameter name must be value.

Offline mode

On remote data binding, all grid actions such as paging, sorting, editing, grouping, filtering, etc, will be processed on server-side. To avoid post back for every action, set the grid to load all data on initialization and make the actions process in client-side. To enable this behavior, use the Offline property of DataManager.

tagHelper
offline.cs
<ejs-grid id="Grid" allowPaging="true" allowSorting="true" allowGrouping="true">
    <e-datamanager url="http://services.odata.org/V4/Northwind/Northwind.svc/Orders" adaptor="ODataV4Adaptor" offline="true" crossdomain="true"></e-datamanager>
    <e-grid-pagesettings pageSize="7"></e-grid-pagesettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
    return View();
}

Sending additional parameters to the server

To add a custom parameter to the data request, use the addParams method of Query class. Assign the Query object with additional parameters to the grid Query property.

tagHelper
params.cs
<ejs-grid id="Grid"  query="new ej.data.Query().addParams('ej2grid', 'true')" >
    <e-datamanager url="http://services.odata.org/V4/Northwind/Northwind.svc/Orders" adaptor="ODataV4Adaptor" crossdomain="true"></e-datamanager>
    <e-grid-pagesettings pageSize="7"></e-grid-pagesettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
 </ejs-grid>
public IActionResult Index()
{
    
    return View();
}

The parameters added using the Query property will be sent along with the data request for every grid action.

Handling HTTP error

During server interaction from the grid, some server-side exceptions may occur, and you can acquire those error messages or exception details in client-side using the ActionFailure event.

The argument passed to the ActionFailure event contains the error details returned from the server.

tagHelper
httperror.cs
<ejs-grid id="Grid"  actionFailure="actionFailure" >
    <e-datamanager url="http://some.com/invalidUrl"></e-datamanager>
    <e-grid-pagesettings pageSize="7"></e-grid-pagesettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="140"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format='yMd' textAlign="Right" width="140"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
<script>
    function actionFailure(args) {
        var span = document.createElement('span');
        this.element.parentNode.insertBefore(span, this.element);
        span.style.color = '#FF0000'
        span.innerHTML = 'Server exception: 404 Not found';
    }
</script>
public IActionResult Index()
{
    
    return View();
}

The ActionFailure event will be triggered not only for the server errors, but also when there is an exception while processing the grid actions.

Handling On-Demand grid actions

On-Demand grid actions help you to improve the performance for large data application. To achieve On-Demand in the grid, use UrlAdaptor. To define UrlAdaptor in the grid, specify the data service in url and the AdaptorType as UrlAdaptor like below.

tagHelper
<ejs-grid id="Grid" allowPaging="true" allowSorting="true" allowFiltering="true" toolbar="@(new List<string>() {"Search" })">
    <e-datamanager url="/Home/UrlDataSource" adaptor="UrlAdaptor"></e-datamanager>
    <e-grid-columns>
        <e-grid-column field="OrderID"  headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>                
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120"></e-grid-column>                
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>                               
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>                
    </e-grid-columns>
</ejs-grid>

After defined DataManager, grid will request an AJAX POST for data. It will be sent to the specified data service for every grid actions with the needed parameters. This query parameters will help you to perform server-side operations for grid.

Parameters Description
RequiresCounts If it is true then the total count of records will be included in response.
Skip Holds the number of records to skip.
Take Holds the number of records to take.
Sorted Contains details about current sorted column and its direction.
Table Defines data source table name.
Where Contains details about current filter column name and its constraints.

The parameters of DataManager bound to DataManagerRequest in the server. You can use Dataoperations and DataManagerRequest to process grid actions such as Paging, Sorting, Searching, and Filtering using the following methods.

Method Names Actions
PerformSkip Bypasses a specified Skip value and returns the remaining collections of records.
PerformTake Bypasses a specified Take value and returns the remaining collections of records.
PerformFiltering Filters a sequence of records based on a predicate.
PerformSorting Sorts the collections of records based on its direction.
PerformSearching Search the records based on a predicate.
dataoperation.cs
public IActionResult UrlDatasource([FromBody]DataManagerRequest dm)
    {
            IEnumerable DataSource = OrdersDetails.GetAllRecords();
            DataOperations operation = new DataOperations();
            if (dm.Search != null && dm.Search.Count > 0)
            {
                DataSource = operation.PerformSearching(DataSource, dm.Search);  //Search
            }
            if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting
            {
                DataSource = operation.PerformSorting(DataSource, dm.Sorted);
            }
            if (dm.Where != null && dm.Where.Count > 0) //Filtering
            {
                DataSource = operation.PerformFiltering(DataSource, dm.Where, dm.Where[0].Operator);
            }
            int count = DataSource.Cast<OrdersDetails>().Count();
            if (dm.Skip != 0)
            {
                DataSource = operation.PerformSkip(DataSource, dm.Skip);   //Paging
            }
            if (dm.Take != 0)
            {
                DataSource = operation.PerformTake(DataSource, dm.Take);
            }
            return dm.RequiresCounts ? Json(new { result = DataSource, count = count }) : Json(DataSource);
    }

DataTable

DataTable represents a table with relational data which has in-built schema to work easily with data column and data row objects.

You can bind DataTable to the grid by using DataSource property. While binding DataTable like below, grid actions such as Sorting, Filtering, Grouping, Paging etc., will handle at client side..

tagHelper
datatable.cs
<ejs-grid id="Grid" dataSource=((System.Data.DataTable)ViewBag.DataSource) allowPaging="true">
            
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer Name" width="150"></e-grid-column>
        <e-grid-column field="EmployeeID" headerText="Employee ID" width="150"></e-grid-column>
        <e-grid-column field="OrderDate" headerText=" Order Date" format="yMd" width="130"></e-grid-column>
   </e-grid-columns>

 </ejs-grid>
public IActionResult Index()
{
     DataTable dt = new DataTable("Table");
            dt.Columns.AddRange(new DataColumn[4] { new DataColumn("OrderID", typeof(long)),
                    new DataColumn("CustomerID", typeof(string)),
                    new DataColumn("EmployeeID",typeof(int)),
                    new DataColumn("OrderDate",typeof(DateTime))
            });
            int code = 10000;
            for (int i = 1; i < 10; i++)
            {
                dt.Rows.Add(code + 1, "ALFKI", i + 0, new DateTime(1991, 05, 15));
                dt.Rows.Add(code + 2, "ANATR", i + 2, new DateTime(1990, 04, 04));
                dt.Rows.Add(code + 3, "ANTON", i + 1, new DateTime(1957, 11, 30));
                dt.Rows.Add(code + 4, "BLONP", i + 3, new DateTime(1930, 10, 22));
                dt.Rows.Add(code + 5, "BOLID", i + 4, new DateTime(1953, 02, 18));
                code += 5;
            }
            ViewBag.dataSource = dt;
            return View();
}

DataTable will be supported from .Net Core 2.0.

DataTable with On-Demand Grid actions

On-Demand grid actions helps you to improve performance for large data application. To perform server side grid actions for DataTable, you need to convert DataTable to IEnumerable using Utils.DataTableToJson method. Thereby in controller action, you need to use DataOperations class for performing grid actions and return result as JSON with result and count pair.

tagHelper
dataoperation.cs
<ejs-grid id="Grid" allowPaging="true" allowSorting="true" allowFiltering="true">
    <e-data-manager url="@Url.Action("UrlDatasource", "Home")" adaptor="UrlAdaptor"></e-data-manager>
    <e-grid-aggregates>
        <e-grid-aggregate>
            <e-aggregate-columns>
                <e-aggregate-column field="EmployeeID" type="Sum"></e-aggregate-column>
            </e-aggregate-columns>
        </e-grid-aggregate>
    </e-grid-aggregates>
    <e-grid-filterSettings type="Excel"></e-grid-filterSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" width="150"></e-grid-column>
        <e-grid-column field="EmployeeID" headerText="Employee ID" textAlign="Right" width="130"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format="yMd" textAlign="Right" width="130"></e-grid-column>
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="130"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public IActionResult UrlDatasource([FromBody]DataManagerRequest dm)
    {
            IEnumerable DataSource = Utils.DataTableToJson(dt); //Here dt is the dataTable
            DataOperations operation = new DataOperations();
            if (dm.Search != null && dm.Search.Count > 0)
            {
                DataSource = operation.PerformSearching(DataSource, dm.Search);  //Search
            }
            if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting
            {
                DataSource = operation.PerformSorting(DataSource, dm.Sorted);
            }
            if (dm.Where != null && dm.Where.Count > 0) //Filtering
            {
                DataSource = operation.PerformFiltering(DataSource, dm.Where, dm.Where[0].Operator);
            }
			List<string> str = new List<string>();
            if (dm.Aggregates != null)
            {           
                for (var i = 0; i < dm.Aggregates.Count; i++)
                    str.Add(dm.Aggregates[i].Field);
            }
            IEnumerable aggregate = operation.PerformSelect(DataSource, str);
            int count = DataSource.Cast<object>().Count();
            if (dm.Skip != 0)
            {
                DataSource = operation.PerformSkip(DataSource, dm.Skip);   //Paging
            }
            if (dm.Take != 0)
            {
                DataSource = operation.PerformTake(DataSource, dm.Take);
            }
            return dm.RequiresCounts ? Json(new { result = DataSource, count = count, aggregate = aggregate }) : Json(DataSource);
    }

DataTable with CRUD operations

To perform server side CRUD operations for DataTable, you need to use InsertUrl, UpdateUrl and RemoveUrl of DataManager for inserting, updating and deleting the records in the specified controller actions.

To pass the data from client side to server side when performing CRUD operations, you need to use ExpandoObject as a parameter for inserting and adding actions.

tagHelper
dataoperation.cs
<ejs-grid id="Grid" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" allowPaging="true">
    <e-data-manager url="/Home/UrlDataSource" adaptor="UrlAdaptor"></e-data-manager>
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120"></e-grid-column>
        <e-grid-column field="EmployeeID" headerText="EmployeeID" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public ActionResult Update(ExpandoObject value)
   {
        IEnumerable data = value.ToList();
        //Here you can Update a record based on your scenario
        return Json(value, JsonRequestBehavior.AllowGet);
    }

       
public ActionResult Insert(ExpandoObject value)
    {
        IEnumerable data = value.ToList();
        //Here you can Insert a record based on your scenario
	    return Json(value, JsonRequestBehavior.AllowGet);
    }
		
public ActionResult Delete(int key)
    {
        //Here you can Delete a record based on your scenario
        return Json(key, JsonRequestBehavior.AllowGet);
    }

Binding with ajax

You can use Grid dataSource property to bind the datasource to Grid from external ajax request. In the below code we have fetched the datasource from the server with the help of ajax request and provided that to dataSource property by using onSuccess event of the ajax.

<script type="text/javascript">
    var grid = document.getElementById('Grid').ej2_instances[0]; // Grid instance
    var ajax = new ej.base.Ajax('/Home/UrlDatasource', 'GET');
    ajax.send();
    ajax.onSuccess = function (data) {
        grid.dataSource = JSON.parse(data).result;
    };
</script>
  • If you bind the dataSource from this way, then it acts like a local dataSource. So you cannot perform any server side crud actions.