Example of Flexible Data in ASP.NET MVC Data Grid Control
This sample demonstrates how to bind a data from various remote services to the Grid component.
Properties
Additional Parameters
HTTP Headers
@Html.AntiForgeryToken()
@Html.UiGrid(new UiGridOptions
{
Id = "Grid",
DataUrl = Url.Action("ODataOrders", "GridDemo"),
Adaptor = UiDataAdaptor.ODataV4,
AllowPaging = true,
PageSize = 12,
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "OrderID", HeaderText = "Order ID", Type = UiColumnType.Number, Width = 120, TextAlign = UiTextAlign.Right, IsPrimaryKey = true },
new UiGridColumn { Field = "CustomerID", HeaderText = "Customer ID", Width = 140 },
new UiGridColumn { Field = "EmployeeID", HeaderText = "Employee ID", Type = UiColumnType.Number, Width = 120, TextAlign = UiTextAlign.Right },
new UiGridColumn { Field = "ShipCity", HeaderText = "Ship City", Width = 140 }
}
})
@Html.AntiForgeryToken()
<style>
.flex-panel .demo-property-row input[type="text"], .flex-panel textarea { width: 100%; }
.flex-panel textarea { height: 45px; }
#payload-detail { margin-bottom: 10px; font-size: 13px; overflow-wrap: anywhere; }
.flex-panel .hide_elem { display: none; }
</style>
<div id="payload-detail"></div>
@Html.UiGrid(new UiGridOptions
{
Id = "Grid",
DataUrl = Url.Action("ODataOrders", "GridDemo"),
Adaptor = UiDataAdaptor.ODataV4,
AllowPaging = true,
PageSize = 12,
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "OrderID", HeaderText = "Order ID", Type = UiColumnType.Number, Width = 120, TextAlign = UiTextAlign.Right, IsPrimaryKey = true },
new UiGridColumn { Field = "CustomerID", HeaderText = "Customer ID", Width = 140 },
new UiGridColumn { Field = "EmployeeID", HeaderText = "Employee ID", Type = UiColumnType.Number, Width = 120, TextAlign = UiTextAlign.Right },
new UiGridColumn { Field = "ShipCity", HeaderText = "Ship City", Width = 140 }
}
})
<div class="demo-property-panel flex-panel">
<h3>Properties</h3>
<div class="demo-property-row"><label for="service_drop">Service</label>
<select id="service_drop">
@foreach (var option in (List<KeyValuePair<string, string>>)ViewData["UrlDataList"]) { <option value="@option.Value" data-url="@option.Key">@option.Key</option> }
</select></div>
<div class="demo-property-row"><label for="adaptor_txt">Adaptor</label><input type="text" id="adaptor_txt" value="ODataV4Adaptor" readonly /></div>
<div class="demo-property-row"><label for="pageCheckbox">Enable Paging</label><input type="checkbox" id="pageCheckbox" checked /></div>
<div class="params_show_hide">
<h4>Additional Parameters</h4>
<div class="demo-property-row"><input type="text" id="paramsKey" placeholder="Enter Name" /><input type="text" id="paramsValue" placeholder="Enter Value" /></div>
<div class="demo-property-row"><button type="button" id="additionalParams">Add</button><textarea id="addParams" rows="2" readonly></textarea></div>
</div>
<div class="header_show_hide">
<h4>HTTP Headers</h4>
<div class="demo-property-row"><input type="text" id="hkey" placeholder="Enter Key" /><input type="text" id="hvalue" placeholder="Enter Value" /></div>
<div class="demo-property-row"><button type="button" id="headerId">Add</button><textarea id="hdvalue" rows="2" readonly></textarea></div>
</div>
<div class="demo-property-row"><button type="button" id="validateSubmit">Connect</button></div>
</div>
<script>
var urls = { ODataV4Adaptor: '@Url.Action("ODataOrders", "GridDemo")', WebApiAdaptor: '@Url.Action("WebApiOrders", "GridDemo")', UrlAdaptor: '@Url.Action("FilterMenuEmployees", "GridDemo")', 'Custom Binding': '@Url.Action("ODataOrders", "GridDemo")' };
var orderColumns = [
{ field: 'OrderID', headerText: 'Order ID', type: 'number', textAlign: 'right', width: 120, isPrimaryKey: true },
{ field: 'CustomerID', headerText: 'Customer ID', width: 140 },
{ field: 'EmployeeID', headerText: 'Employee ID', type: 'number', textAlign: 'right', width: 120 },
{ field: 'ShipCity', headerText: 'Ship City', width: 140 }
];
var employeeColumns = [
{ field: 'EmployeeID', headerText: 'Employee ID', type: 'number', textAlign: 'right', width: 130, isPrimaryKey: true },
{ field: 'Employees', headerText: 'Employee Name', width: 150 },
{ field: 'Designation', headerText: 'Designation', width: 130 },
{ field: 'CurrentSalary', headerText: 'Current Salary', type: 'number', format: 'C2', textAlign: 'right', width: 140 }
];
function describe() {
var adaptor = document.getElementById('service_drop').value;
document.getElementById('payload-detail').innerHTML = '';
var box = document.getElementById('payload-detail');
var title = document.createElement('b');
title.textContent = 'Payload Information';
box.appendChild(title);
[['Service URL', urls[adaptor]], ['Adaptor Type', adaptor], ['Request', adaptor === 'UrlAdaptor' ? 'POST with the page, sort and filters as JSON' : 'GET with $skip, $top, $orderby, $filter and a count']].forEach(function (line) {
box.appendChild(document.createElement('br'));
box.appendChild(document.createTextNode(line[0] + ': ' + line[1]));
});
}
describe();
// The additional boxes keep one JSON object per line (as Syncfusion's), for the parameters and the headers.
function addLine(keyId, valueId, areaId) {
var key = document.getElementById(keyId).value.trim();
if (!key) { return; }
var line = {};
line[key] = document.getElementById(valueId).value;
var area = document.getElementById(areaId);
area.value += (area.value ? '\n' : '') + JSON.stringify(line);
document.getElementById(keyId).value = '';
document.getElementById(valueId).value = '';
}
function lines(areaId) {
var merged = {};
document.getElementById(areaId).value.split('\n').filter(Boolean).forEach(function (text) { Object.assign(merged, JSON.parse(text)); });
return merged;
}
document.getElementById('additionalParams').addEventListener('click', function () { addLine('paramsKey', 'paramsValue', 'addParams'); });
document.getElementById('headerId').addEventListener('click', function () { addLine('hkey', 'hvalue', 'hdvalue'); });
document.getElementById('service_drop').addEventListener('change', function (e) {
document.getElementById('adaptor_txt').value = e.target.value;
var custom = e.target.value === 'Custom Binding';
Array.prototype.forEach.call(document.querySelectorAll('.params_show_hide, .header_show_hide'), function (el) { el.classList.toggle('hide_elem', custom); });
describe();
});
// Syncfusion's Connect: the grid is bound to the chosen service with its adaptor (and the columns of its data); the paging box turns the pager on or off.
document.getElementById('validateSubmit').addEventListener('click', function () {
var adaptor = document.getElementById('service_drop').value;
var paged = document.getElementById('pageCheckbox').checked;
var params = lines('addParams');
var headers = lines('hdvalue');
window.Lumen.get('Grid').setSettings({ pageSize: paged ? 12 : 0 }).then(function (grid) {
if (adaptor === 'Custom Binding') {
// the page is read by this script (a GET with $skip, $top and $count) and its rows are bound
fetch(urls[adaptor] + '?$top=1000&$count=true', { headers: { Accept: 'application/json' } }).then(function (r) { return r.json(); }).then(function (data) {
grid.changeDataSource(data.value, orderColumns);
});
return;
}
var source = { dataUrl: urls[adaptor], serverOperations: true, params: params, headers: headers, adaptor: adaptor === 'ODataV4Adaptor' ? 'odatav4' : adaptor === 'WebApiAdaptor' ? 'webapi' : 'url' };
grid.changeDataSource(source, adaptor === 'UrlAdaptor' ? employeeColumns : orderColumns);
});
});
</script>
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class GridController : Controller
{
// The page is Views/Grid/FlexibleData.cshtml; it draws what ViewData holds.
public ActionResult FlexibleData()
{
ViewData["UrlDataList"] = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("OData v4 service (ODataV4Adaptor)", "ODataV4Adaptor"),
new KeyValuePair<string, string>("Web API service (WebApiAdaptor)", "WebApiAdaptor"),
new KeyValuePair<string, string>("Controller action (UrlAdaptor)", "UrlAdaptor"),
new KeyValuePair<string, string>("OData v4 service read by script (Custom Binding)", "Custom Binding")
};
return View();
}
/// <summary>One order: the rows of Syncfusion's Grid samples that use the orders.</summary>
public class OrdersDetails
{
public OrdersDetails()
{
}
public OrdersDetails(int OrderID, string CustomerId, int EmployeeId, double Freight, bool Verified, DateTime OrderDate, string ShipCity, string ShipName, string ShipCountry, DateTime ShippedDate, string ShipAddress)
{
this.OrderID = OrderID;
this.CustomerID = CustomerId;
this.EmployeeID = EmployeeId;
this.Freight = Freight;
this.ShipCity = ShipCity;
this.Verified = Verified;
this.OrderDate = OrderDate;
this.ShipName = ShipName;
this.ShipCountry = ShipCountry;
this.ShippedDate = ShippedDate;
this.ShipAddress = ShipAddress;
}
public int OrderID { get; set; }
public string CustomerID { get; set; }
public int EmployeeID { get; set; }
public double Freight { get; set; }
public string ShipCity { get; set; }
public bool Verified { get; set; }
public DateTime OrderDate { get; set; }
public string ShipName { get; set; }
public string ShipCountry { get; set; }
public DateTime ShippedDate { get; set; }
public string ShipAddress { get; set; }
public static List<OrdersDetails> GetAllRecords()
{
List<OrdersDetails> order = new List<OrdersDetails>();
int code = 10000;
for (int i = 1; i < 10; i++)
{
order.Add(new OrdersDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, new DateTime(1991, 05, 15, 10, 40, 00), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7, 16, 09, 30, 00), "Kirchgasse 6"));
order.Add(new OrdersDetails(code + 2, "ANATR", i + 2, 3.3 * i, true, new DateTime(1990, 04, 04, 09, 30, 00), "Madrid", "Queen Cozinha", "Brazil", new DateTime(1996, 9, 11, 03, 45, 00), "Avda. Azteca 123"));
order.Add(new OrdersDetails(code + 3, "ANTON", i + 1, 4.3 * i, true, new DateTime(1957, 11, 30, 03, 45, 00), "Cholchester", "Frankenversand", "Germany", new DateTime(1996, 10, 7, 07, 50, 00), "Carrera 52 con Ave. Bolívar #65-98 Llano Largo"));
order.Add(new OrdersDetails(code + 4, "BLONP", i + 3, 5.3 * i, false, new DateTime(1930, 10, 22, 07, 30, 00), "Marseille", "Ernst Handel", "Austria", new DateTime(1996, 12, 30, 06, 12, 00), "Magazinweg 7"));
order.Add(new OrdersDetails(code + 5, "BOLID", i + 4, 6.3 * i, true, new DateTime(1953, 02, 18, 05, 50, 00), "Tsawassen", "Hanari Carnes", "Switzerland", new DateTime(1997, 12, 3, 12, 50, 00), "1029 - 12th Ave. S."));
code += 5;
}
return order;
}
}
/// <summary>
/// The 10,000 employees the Filter Menu sample reads from its server action (Syncfusion's sample reads the same
/// count from its remote service): EmployeeID, Employees (the name), Designation and CurrentSalary.
/// </summary>
public class FilterMenuEmployee
{
private static List<FilterMenuEmployee> all;
public int EmployeeID { get; set; }
public string Employees { get; set; }
public string Designation { get; set; }
public double CurrentSalary { get; set; }
public static List<FilterMenuEmployee> GetAllRecords()
{
if (all == null)
{
string[] first = { "Anne", "Michael", "Margaret", "Janet", "Nancy", "Robert", "Steven", "Laura", "Andrew", "Albert", "Maria", "Frank", "Ann", "Paul", "Karin", "Hanna" };
string[] last = { "King", "Davolio", "Fuller", "Leverling", "Peacock", "Buchanan", "Suyama", "Callahan", "Dodsworth", "Hellstern", "Smith", "Wilson", "Taylor", "Brown", "Moore", "Clark" };
string[] titles = { "Sales Representative", "Vice President", "Sales Manager", "Inside Sales Coordinator", "Software Engineer", "Marketing Specialist", "Accountant", "Support Engineer" };
var list = new List<FilterMenuEmployee>();
for (int i = 0; i < 10000; i++)
{
list.Add(new FilterMenuEmployee
{
EmployeeID = 10001 + i,
Employees = first[i % first.Length] + " " + last[(i / first.Length) % last.Length],
Designation = titles[(i * 7) % titles.Length],
CurrentSalary = 30000 + (i * 137) % 70000
});
}
all = list;
}
return all;
}
}
/// <summary>
/// The Flexible Data sample's OData v4 service: $skip, $top, $count, $orderby and $filter become a UiDataRequest
/// (UiODataQuery) that UiDataOperations answers; the result is { value, "@odata.count" }.
/// </summary>
[HttpGet]
public ActionResult ODataOrders()
{
UiDataRequest request = ODataRequest();
var result = UiDataOperations.Execute(OrdersDetails.GetAllRecords().AsQueryable(), request, "OrderID");
return Json(new Dictionary<string, object> { { "value", result.Result }, { "@odata.count", result.Count } }, JsonRequestBehavior.AllowGet);
}
/// <summary>The Flexible Data sample's Web API service: the same query options; the result is { Items, Count }.</summary>
[HttpGet]
public ActionResult WebApiOrders()
{
UiDataRequest request = ODataRequest();
var result = UiDataOperations.Execute(OrdersDetails.GetAllRecords().AsQueryable(), request, "OrderID");
return Json(new Dictionary<string, object> { { "Items", result.Result }, { "Count", result.Count } }, JsonRequestBehavior.AllowGet);
}
private UiDataRequest ODataRequest()
{
int skip, top;
int.TryParse(Request.QueryString["$skip"], out skip);
int.TryParse(Request.QueryString["$top"], out top);
return UiODataQuery.ToRequest(skip, top, Request.QueryString["$orderby"], Request.QueryString["$filter"], Request.QueryString["$search"]);
}
/// <summary>The Filter Menu sample's 10,000 employees: UiDataOperations.Execute pages, sorts and filters them (and answers the filter popups' lists of values).</summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult FilterMenuEmployees(UiDataRequest request)
{
return Json(UiDataOperations.Execute(FilterMenuEmployee.GetAllRecords().AsQueryable(), request, "EmployeeID"));
}
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>
@* Grids with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@
The Grid supports data binding. The dataSource property can be assigned with the instance of DataManager to bind remote data.
The DataManager, which will act as an interface between the service endpoint and the Grid, will require the below minimal information to interact with service endpoint properly.
DataManager->url- Defines the service endpoint to fetch dataDataManager->adaptor- Defines the adaptor option.
Adaptor is responsible for processing response and request from/to the service endpoint. syncfusion/ej2-data package provides some predefined adaptors which are designed to interact with particular service endpoints. They are,
-
UrlAdaptor- Use this to interact any remote services. This is the base adaptor for all remote based adaptors. ODataV4Adaptor- Use this to interact with OData V4 endpoints.WebApiAdaptor- Use this to interact with Web API created under OData standards.- Own Service - Custom databinding is used where data actions like paging, sorting are perfromed in
dataStateChangeevent of grid.
By default ODataV4Adaptor is used in this demo. The adaptor type will be automatically assigned based on the selected data service.
The dataSource of grid can be dynamically changed using changeDataSource method by following the below steps
- Select any URL from the Service dropdown.
- To enable or disable the paging feature, check or uncheck the Enable Paging checkbox.
- Enter the name and value in the respective input boxes, then click the Add button to send extra parameters with the grid query. However, note that this demonstration only covers the skip and take query from the additional parameters, excluding the custom binding feature.
- In this demo, if you enable pagination by checking the Enable Paging checkbox, the additional parameter of skip and take query will not be processed separately, as it will be processed inbuilt with the pagination feature.
- To add http request headers enter the key and value in the respective input fields and click the Add button.
- In this demo, custom headers are not included in the payload information due to the limitations of both the OData service and the custom binding service. These services do not accept any additional headers based on the CORS policy. To send HTTP headers, it is important to ensure the CORS policy in your service.
- Multiple headers and parameters can be added as well.
- Press the Connect button to update the grid dataSource.
- The connected service with the respective adaptor, the parameters and header that passed along with the grid query will be listed under Payload Information.