- Loading indicator
- Refresh the datasource using property
- Dynamically change the datasource or columns or both
- DataTable
- DataTable with CRUD operations
- Prevent to convert local time zone format for date column
- How to set custom headers using a custom adaptor in Syncfusion ASP.NET MVC Grid
- Troubleshoot: Syncfusion ASP.NET MVC Grid render rows without data
Contact Support
Data binding in ASP.NET MVC Grid
11 Apr 202524 minutes to read
Data binding is a fundamental technique that empowers the Syncfusion ASP.NET MVC Grid to integrate data into its interface, enabling the creation of dynamic and interactive Grid views. This feature is particularly valuable when working with large datasets or when data needs to be fetched remotely.
The Grid utilizes the DataManager, which supports both local binding with JavaScript object arrays and remote binding with RESTful JSON data services. The key property, DataSource, can be assigned to a DataManager instance or a collection of JavaScript object arrays.
It supports following data binding methods:
- List binding
- DataTable binding
- Remote data
Loading indicator
The Syncfusion ASP.NET MVC Grid offers a loading animation feature, which makes it easy to identify when data is being loaded or refreshed. This feature provides a clear understanding of the Grid current state and actions, such as sorting, filtering, grouping, and more.
To achieve this, you can utilize the LoadingIndicator.IndicatorType
property of the Grid, which supports two types of indicators:
- Spinner (default indicator)
- Shimmer
The following example demonstrates how to set the LoadingIndicator.IndicatorType
property based on changing the dropdown value using the Change event of the DropDownList. The refreshColumns
method is used to apply the changes and display the updated loading indicator type.
@{
var dropDownData = new[] {
new { value = "Shimmer", text = "Shimmer" },
new { value = "Spinner", text = "Spinner" },
};
}
<div style="padding-bottom: 20px; display: flex">
<label style="padding: 5px 10px 0 0;font-weight: bold"> Change the loading indicator type:</label>
<span style="height:fit-content">
<ejs-dropdownlist id="dropDown" dataSource="dropDownData" index="0" width="150px" change="valueChange">
</ejs-dropdownlist>
</span>
</div>
<ejs-grid id="grid" allowPaging="true" height="348px" allowSorting="true" allowFiltering="true">
<e-grid-loadingIndicator indicatorType="Shimmer"></e-grid-loadingIndicator>
<e-data-manager url="https://services.syncfusion.com/aspnet/production/api/UrlDataSource" adaptor="UrlAdaptor"></e-data-manager>
<e-grid-columns>
<e-grid-column field="EmployeeID" headerText="Employee ID" textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="Employees" headerText="Employees" width="150"></e-grid-column>
<e-grid-column field="Designation" headerText="Designation" width="115"></e-grid-column>
<e-grid-column field="CurrentSalary" headerText="Current Salary" width="150" textAlign="Right"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
function valueChange(args) {
var grid = document.getElementById("grid").ej2_instances[0];
grid.loadingIndicator.indicatorType = document.getElementById("dropDown").ej2_instances[0].value;
grid.refreshColumns();
}
</script>
public ActionResult Index()
{
return view();
}
Refresh the datasource using property
Refreshing the data source in a Syncfusion ASP.NET MVC Grid involves updating the data that the Grid displays dynamically. This operation is essential when you need to reflect changes in the underlying data without reloading the entire page or component.
To achieve this, you can make use of the DataSource property in conjunction with the setProperties
method. This ensures that the Grid reflects the changes in the data source without requiring a complete page or component reload.
For example, if you add or delete data source records, follow these steps:
Step 1: Add/delete the data source record by using the following code.
var grid = document.getElementById("grid").ej2_instances[0];
grid.dataSource.unshift(data); // Add a new record.
grid.dataSource.splice(selectedRow, 1); // Delete a record.
Step 2: Refresh the data source after changes by invoking the setProperties
method.
grid.setProperties({ dataSource: grid.dataSource});
The following example demonstrates adding a new record to the data source through an external button:
<div style="padding: 10px 0px 20px 0px">
<ejs-button id="sample" cssClass="e-primary" content="Refresh Datasource"></ejs-button>
</div>
<ejs-grid id="grid" dataSource="@ViewBag.DataSource" height="348px">
<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="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
document.getElementById('sample').addEventListener('click', function () {
changeDatasource();
});
function changeDatasource() {
var grid = document.getElementById("grid").ej2_instances[0];
for (let i = 0; i < 5; i++) {
let newRecord = {
OrderID: generateOrderId(),
CustomerID: generateCustomerId(),
ShipCity: generateShipCity(),
Freight: generateFreight(),
ShipName: generateShipName()
};
grid.dataSource.unshift(newRecord);
grid.setProperties({dataSource: grid.dataSource });
}
// Generate a random OrderID.
function generateOrderId() {
return Math.floor(10000 + Math.random() * 90000);
}
// Generate a random CustomerID.
function generateCustomerId() {
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = 0; i < 5; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
// Generate a random ShipCity.
function generateShipCity() {
let cities = ['London', 'Paris', 'New York', 'Tokyo', 'Berlin'];
return cities[Math.floor(Math.random() * cities.length)];
}
// Generate a random Freight value.
function generateFreight() {
return Math.random() * 100;
}
// Generate a random ShipName.
function generateShipName() {
let names = ['Que Delícia', 'Bueno Foods', 'Island Trading', 'Laughing Bacchus Winecellars'];
return names[Math.floor(Math.random() * names.length)];
}
}
</script>
public ActionResult Index()
{
ViewBag.DataSource = OrderDetails.GetAllRecords();
return View();
}
Dynamically change the datasource or columns or both
The Syncfusion ASP.NET MVC Grid allows dynamic modification of the data source, columns, or both . This feature is particularly valuable when you need to refresh the Grid’s content and structure without requiring a complete page reload.
To achieve dynamic changes, you can utilize the changeDataSource
method. This method enables you to update the data source, columns, or both, based on your application’s requirements. However, it is important to note that during the changing process for the data source and columns, Grid existing actions such as sorting, filtering, grouping, aggregation, and searching will be reset.The changeDataSource
method has two optional arguments: the first argument represents the data source, and the second argument represents the columns. The various uses of the changeDataSource
method are explained in the following topic.
1. Change both data source and columns:
To modify both the existing columns and the data source, you need to pass the both arguments to the changeDataSource
method. The following example demonstrates how to change both the data source and columns.
You can assign a JavaScript object array to the DataSource property to bind local data to the Grid. The code below provides an example of how to create a data source for the Grid.
export let data= [
{
OrderID: 10248, CustomerID: 'VINET', Freight: 32.38,
ShipCity: 'Reims'
},
{
OrderID: 10249, CustomerID: 'TOMSP', Freight: 11.61,
ShipCity: 'Münster'
},
{
OrderID: 10250, CustomerID: 'HANAR', Freight: 61.34,
ShipCity: 'Rio de Janeiro'
}];
The following code demonstrates how to create the Columns for the Grid, which are based on the provided Grid data source.
newColumn= [
{ field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 125 },
{ field: 'CustomerID', headerText: 'Customer ID', width: 125 },
];
The following code demonstrates updating the data source and columns defined above using the changeDataSource
method.
var grid = document.getElementById("grid").ej2_instances[0];
grid.changeDataSource(data, newColumn);
2. Modify only the existing columns:
To modify the existing columns in a Grid, you can either add or remove columns or change the entire set of columns using the changeDataSource
method. To use this method, you should set the first parameter to null and provide the new columns as the second parameter. However, please note that if a column field is not specified in the data source, its corresponding column values will be empty. The following example illustrates how to modify existing columns.
The following code demonstrates how to add new columns with existing Grid columns (‘newColumn’) by using changeDataSource
method.
var grid = document.getElementById("grid").ej2_instances[0];
newColumn1= [
{ field: 'Freight', headerText: 'Freight', textAlign: 'Right', width: 125 },
{ field: 'ShipCity', headerText: 'ShipCity', width: 125 },
];
let column = this.newColumn.push(...this.newColumn1);
grid.changeDataSource(null, column);
3. Modify only the data source:
You can change the entire data source in the Grid using the changeDataSource
method. To use this method, you should provide the data source as the first argument, and the second argument which is optional can be used to specify new columns for the Grid. If you are not specifying the columns, the Grid will generate the columns automatically based on the data source. The following example demonstrates how to modify the data source.
You can assign a JavaScript object array to the DataSource property to bind local data to the Grid. The code below provides an example of how to create a new data source for the Grid.
export let employeeData = [
{
FirstName: 'Nancy', City: 'Seattle', Region: 'WA',
Country: 'USA'
},
{
FirstName: 'Andrew', City: 'London', Region: null,
Country: 'UK',
},
{
FirstName: 'Janet', City: 'Kirkland', Region: 'WA',
Country: 'USA'
}];
The following code demonstrates, how to use the changeDataSource
method to bind the new employeeData to the Grid.
var grid = document.getElementById("grid").ej2_instances[0];
grid.changeDataSource(employeeData);
@using Newtonsoft.Json
<div style="padding: 10px 0px 20px 0px">
<ejs-button id="sample" cssClass="e-primary" content="Change datasource and column"></ejs-button>
</div>
<ejs-grid id="grid" dataSource="@ViewBag.DataSource" allowPaging="true">
<e-grid-pagesettings pageCount=3 pageSize=5 ></e-grid-pagesettings>
<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="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
var count = 0;
var newColumn = [
{ field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 125 },
{ field: 'CustomerName', headerText: 'Customer Name', width: 125 },
{ field: 'OrderDate', headerText: 'Order Date', width: 130, type: 'date', format:'yMd', textAlign: 'Right' },
{ field: 'Freight', headerText: 'Freight', width: 120, textAlign: 'Right' },
];
document.getElementById('sample').addEventListener('click', function () {
var grid = document.getElementById("grid").ej2_instances[0];
count = count + 100;
grid.changeDataSource(@Html.Raw(JsonConvert.SerializeObject(ViewBag.DataSource)), newColumn);
});
</script>
public ActionResult Index()
{
ViewBag.DataSource = OrderDetails.GetAllRecords();
return View();
}
- The Grid state persistence feature does not support the
changeDataSource
method.- In this document, the above sample uses the local data for
changeDataSource
method. For those using a remote data source, refer to the FlexibleData resource.
DataTable
The DataTable feature represents a structured table with relational data, equipped with an in-built schema that simplifies working with data column and row objects. This allows for a more intuitive way to manage and display complex data in the Syncfusion ASP.NET MVC Grid.
To bind a DataTable to the Grid, utilize the dataSource property. When you bind a DataTable, Grid actions such as Sorting, Filtering, Grouping, and Paging are processed on the client side, enhancing performance and responsiveness.
Here’s how to bind a DataTable
to the Grid:
<ejs-grid id="grid" dataSource=((System.Data.DataTable)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="Freight" headerText="Freight" 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="ShipCity" headerText="Ship City" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
public ActionResult Index()
{
DataTable ordersTable = new DataTable("Orders");
ordersTable.Columns.AddRange(new DataColumn[5]
{
new DataColumn("OrderID", typeof(long)),
new DataColumn("CustomerID", typeof(string)),
new DataColumn("Freight", typeof(decimal)),
new DataColumn("OrderDate", typeof(DateTime)),
new DataColumn("ShipCity", typeof(string))
});
ordersTable.Rows.Add(10001, "ALFKI", 29.75m, new DateTime(1991, 05, 15), "Berlin");
ordersTable.Rows.Add(10002, "ANATR", 15.00m, new DateTime(1990, 04, 04), "Madrid");
ordersTable.Rows.Add(10003, "ANTON", 22.50m, new DateTime(1957, 11, 30), "London");
ordersTable.Rows.Add(10004, "BLONP", 40.25m, new DateTime(1930, 10, 22), "Paris");
ordersTable.Rows.Add(10005, "BOLID", 19.95m, new DateTime(1953, 02, 18), "New York");
ordersTable.Rows.Add(10006, "VINET", 55.00m, new DateTime(1997, 01, 21), "Toulouse");
ordersTable.Rows.Add(10007, "TOMSP", 80.50m, new DateTime(2000, 06, 17), "London");
ordersTable.Rows.Add(10008, "MORGK", 45.25m, new DateTime(1996, 03, 30), "Berlin");
ordersTable.Rows.Add(10009, "RICSU", 30.15m, new DateTime(1995, 05, 11), "Madrid");
ordersTable.Rows.Add(10010, "SUPRD", 90.00m, new DateTime(1999, 08, 23), "Paris");
ViewBag.DataSource = ordersTable;
return View();
}
NOTE
DataTable
will be supported from .Net Core 2.0.
DataTable with on-demand Grid actions
The On-Demand Grid Actions feature in Syncfusion ASP.NET MVC Grid enables server-side processing of Grid actions, such as sorting, filtering, grouping, and paging. This is especially useful for applications with large datasets, where client-side operations can impact performance.
To implement on-demand server-side actions with a DataTable, you need to:
-
Convert the
DataTable
to an IEnumerable object. -
Use the DataOperations class in the controller to process Grid actions like sorting, filtering, and paging.
-
Return the result as a JSON object with a result (data) and count (total record count) pair.
@{
string fullUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}";
}
@Html.AntiForgeryToken()
<ejs-grid id="grid" allowPaging="true" allowSorting="true" load="gridLoad" allowFiltering="true" toolbar="@(new List<string>() { "Search"})">
<e-data-manager url="@fullUrl?handler=UrlDatasource" adaptor="UrlAdaptor"></e-data-manager>
<e-grid-aggregates>
<e-grid-aggregate>
<e-aggregate-columns>
<e-aggregate-column field="Freight" 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 Name" width="150"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" editType="numericedit" textAlign="Right" format="C2" width="130"></e-grid-column>
<e-grid-column field="OrderDate" headerText="Order Date" editType="datepickeredit" format="yMd" textAlign="Right" width="130"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" editType="dropdownedit" width="130"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
function gridLoad() {
this.dataSource.dataSource.headers = [{ 'XSRF-TOKEN': document.querySelector('input[type="hidden"][name="__RequestVerificationToken"]').value }];
}
</script>
public ActionResult OnPostUrlDatasource([FromBody] DataManagerRequest dataManagerRequest)
{
DataTable ordersTable = new DataTable("Orders");
ordersTable.Columns.AddRange(new DataColumn[6]
{
new DataColumn("OrderID", typeof(long)),
new DataColumn("CustomerID", typeof(string)),
new DataColumn("Freight", typeof(decimal)),
new DataColumn("OrderDate", typeof(DateTime)),
new DataColumn("ShipCity", typeof(string)),
new DataColumn("EmployeeID", typeof(int))
});
ordersTable.Rows.Add(10001, "ALFKI", 29.75m, new DateTime(1991, 05, 15), "Berlin", 1);
ordersTable.Rows.Add(10002, "ANATR", 15.00m, new DateTime(1990, 04, 04), "Madrid", 2);
ordersTable.Rows.Add(10003, "ANTON", 22.50m, new DateTime(1957, 11, 30), "London", 3);
ordersTable.Rows.Add(10004, "BLONP", 40.25m, new DateTime(1930, 10, 22), "Paris", 4);
ordersTable.Rows.Add(10005, "BOLID", 19.95m, new DateTime(1953, 02, 18), "New York", 5);
ordersTable.Rows.Add(10006, "VINET", 55.00m, new DateTime(1997, 01, 21), "Toulouse", 6);
ordersTable.Rows.Add(10007, "TOMSP", 80.50m, new DateTime(2000, 06, 17), "London", 7);
ordersTable.Rows.Add(10008, "MORGK", 45.25m, new DateTime(1996, 03, 30), "Berlin", 8);
ordersTable.Rows.Add(10009, "RICSU", 30.15m, new DateTime(1995, 05, 11), "Madrid", 9);
ordersTable.Rows.Add(10010, "SUPRD", 90.00m, new DateTime(1999, 08, 23), "Paris", 10);
IEnumerable DataSource = ordersTable.AsEnumerable()
.Select(row => new
{
OrderID = row.Field<long>("OrderID"),
CustomerID = row.Field<string>("CustomerID"),
Freight = row.Field<decimal>("Freight"),
OrderDate = row.Field<DateTime>("OrderDate"),
ShipCity = row.Field<string>("ShipCity"),
EmployeeID = row.Field<int>("EmployeeID")
});
DataOperations operation = new DataOperations();
if (dataManagerRequest.Search != null && dataManagerRequest.Search.Count > 0)
{
DataSource = operation.PerformSearching(DataSource, dataManagerRequest.Search);
}
if (dataManagerRequest.Sorted != null && dataManagerRequest.Sorted.Count > 0)
{
DataSource = operation.PerformSorting(DataSource, dataManagerRequest.Sorted);
}
if (dataManagerRequest.Where != null && dataManagerRequest.Where.Count > 0)
{
DataSource = operation.PerformFiltering(DataSource, dataManagerRequest.Where, dataManagerRequest.Where[0].Operator);
}
List<string> str = new List<string>();
if (dataManagerRequest.Aggregates != null)
{
for (var i = 0; i < dataManagerRequest.Aggregates.Count; i++)
str.Add(dataManagerRequest.Aggregates[i].Field);
}
IEnumerable aggregate = operation.PerformSelect(DataSource, str);
int count = DataSource.Cast<object>().Count();
if (dataManagerRequest.Skip != 0)
{
DataSource = operation.PerformSkip(DataSource, dataManagerRequest.Skip);
}
if (dataManagerRequest.Take != 0)
{
DataSource = operation.PerformTake(DataSource, dataManagerRequest.Take);
}
return dataManagerRequest.RequiresCounts ? new JsonResult(new { result = DataSource, count = count, aggregate = aggregate }) : new JsonResult(DataSource);
}
DataTable with CRUD operations
The Syncfusion ASP.NET MVC Grid supports server-side CRUD (Create, Read, Update, Delete) operations using a DataTable as the underlying data source. This feature is particularly useful for applications that require dynamic data management with efficient performance and scalability.
To perform server-side CRUD operations for a DataTable, you need to utilize the InsertUrl, UpdateUrl, and RemoveUrl properties of the DataManager. These properties allow you to specify the controller actions for inserting, updating, and deleting records.
When passing data from the client side to the server side during CRUD operations, use ExpandoObject as a parameter for the insert and update actions. This approach allows you to handle dynamic data structures effectively.
Here’s a sample implementation demonstrating how to set up the Grid for CRUD operations with a DataTable:
@Html.EJS().Grid("grid").DataSource(ds => ds.Url("/Home/UrlDatasource").InsertUrl("/Home/Insert").RemoveUrl("/Home/Delete").UpdateUrl("/Home/Update").Adaptor("UrlAdaptor")).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("120").Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("130").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCity").HeaderText("Ship City").Width("120").Add();
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
public class HomeController : Controller
{
private static DataTable ordersTable = GetData();
public ActionResult Index()
{
return View();
}
// Method to populate the DataTable with initial data.
private static DataTable GetData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] {
new DataColumn("OrderID", typeof(int)),
new DataColumn("CustomerID", typeof(string)),
new DataColumn("EmployeeID", typeof(int)),
new DataColumn("Freight", typeof(double)),
new DataColumn("ShipCity", typeof(string)),
});
int code = 1000;
int id = 0;
for (int i = 1; i <= 15; i++)
{
dt.Rows.Add(code + 1, "ALFKI", id + 1, 2.3 * i, "New York");
dt.Rows.Add(code + 2, "ANATR", id + 2, 3.3 * i, "Los Angeles");
dt.Rows.Add(code + 3, "ANTON", id + 3, 4.3 * i, "Chicago");
dt.Rows.Add(code + 4, "BLONP", id + 4, 5.3 * i, "Houston");
dt.Rows.Add(code + 5, "BOLID", id + 5, 6.3 * i, "Miami");
code += 5;
id += 5;
}
return dt;
}
// Data Source for Syncfusion Grid.
public ActionResult UrlDatasource(DataManagerRequest dm)
{
IEnumerable DataSource = Utils.DataTableToJson(ordersTable);
DataOperations operation = new DataOperations();
int count = DataSource.Cast<object>().Count();
if (dm.Skip != 0)
{
DataSource = operation.PerformSkip(DataSource, dm.Skip);
}
if (dm.Take != 0)
{
DataSource = operation.PerformTake(DataSource, dm.Take);
}
return dm.RequiresCounts ? Json(new { result = DataSource, count = count }) : Json(DataSource);
}
// Insert action (Adding new record at the **top**).
public ActionResult Insert(ExpandoObject value)
{
if (value != null)
{
DataRow newRow = ordersTable.NewRow();
var dict = (IDictionary<string, object>)value;
newRow["OrderID"] = dict.ContainsKey("OrderID") ? dict["OrderID"] : 0;
newRow["CustomerID"] = dict.ContainsKey("CustomerID") ? dict["CustomerID"].ToString() : string.Empty;
newRow["EmployeeID"] = dict.ContainsKey("EmployeeID") ? Convert.ToInt32(dict["EmployeeID"]) : 0;
newRow["Freight"] = dict.ContainsKey("Freight") ? Convert.ToDouble(dict["Freight"]) : 0;
newRow["ShipCity"] = dict.ContainsKey("ShipCity") ? dict["ShipCity"].ToString() : string.Empty;
ordersTable.Rows.InsertAt(newRow, 0); // Insert at the top.
}
return Json(value, JsonRequestBehavior.AllowGet);
}
public ActionResult Update(ExpandoObject value)
{
if (value != null)
{
var dict = (IDictionary<string, object>)value;
long orderId = dict.ContainsKey("OrderID") ? Convert.ToInt32(dict["OrderID"]) : 0;
DataRow rowToUpdate = ordersTable.Rows.Cast<DataRow>().FirstOrDefault(row => row.Field<int>("OrderID") == orderId);
if (rowToUpdate != null)
{
rowToUpdate["CustomerID"] = dict.ContainsKey("CustomerID") ? dict["CustomerID"].ToString() : string.Empty;
rowToUpdate["EmployeeID"] = dict.ContainsKey("EmployeeID") ? Convert.ToInt32(dict["EmployeeID"]) : 0;
rowToUpdate["Freight"] = dict.ContainsKey("Freight") ? Convert.ToDouble(dict["Freight"]) : 0;
rowToUpdate["ShipCity"] = dict.ContainsKey("ShipCity") ? dict["ShipCity"].ToString() : string.Empty;
}
}
return Json(value, JsonRequestBehavior.AllowGet);
}
public ActionResult Delete(int key)
{
var rowToDelete = ordersTable.AsEnumerable().FirstOrDefault(row => row.Field<int>("OrderID") == key);
if (rowToDelete != null)
{
ordersTable.Rows.Remove(rowToDelete);
}
return Json(new { Key = key }, JsonRequestBehavior.AllowGet);
}
}
Prevent to convert local time zone format for date column
By default, Syncfusion ASP.NET MVC Grid automatically converts date values to the local time zone of the client system. However, in some scenarios, you may need to display the original date as received from the server without any timezone conversion.
To prevent timezone conversion for a date column, use the serverTimezoneOffset
property from DataUtil
. Setting this property to 0 ensures that dates remain in the original format received from the server without conversion to the local timezone.
The following example demonstrates how to prevent local time zone conversion for date columns in Syncfusion ASP.NET MVC Grid by using the DataUtil.serverTimezoneOffset
property:
@{
ViewBag.Title = "Syncfusion Grid with Timezone Selection";
}
@using Syncfusion.EJ2
<div style="display: flex; align-items: center; margin-bottom: 10px;" >
<label style="margin-right: 10px">Select Timezone:</label>
@Html.EJS().DropDownList("timezone").DataSource((IEnumerable < object >)ViewBag.TimeZones).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Value = "Value", Text = "Text" }).Index(0).Width("200px").Change("onTimezoneChange").Render()
</div >
<div style="margin-bottom: 20px;">
@Html.EJS().CheckBox("timezoneCheckbox").Label("Prevent Timezone Conversion").Change("onCheckboxChange").Render()
</div>
<div>
@*Replace xxxx with your actual port number.*@
@Html.EJS().Grid("Grid").DataSource(dm => dm.Url("https://localhost:****/api/orders").Adaptor("WebApiAdaptor")).AllowPaging().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).IsPrimaryKey(true).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("140").Add();
col.Field("Freight").HeaderText("Freight").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("140").Format("dd/MM/yyyy HH:mm").Add();
}).Load("load").Render()
</div>
<script>
var selectedTimezone = -12;
var checkbox;
var grid;
function load() {
checkbox = document.getElementById("timezoneCheckbox")?.ej2_instances?.[0];
grid = document.getElementById("Grid")?.ej2_instances?.[0];
ej.data.DataUtil.serverTimezoneOffset = checkbox.checked ? 0 : selectedTimezone;
}
function onTimezoneChange(event) {
selectedTimezone = Number(event.value);
ej.data.DataUtil.serverTimezoneOffset = checkbox.checked ? 0 : selectedTimezone;
grid.setProperties({
dataSource: new ej.data.DataManager({
url: "https://localhost:****/api/orders", // Replace **** with your actual port number.
adaptor: new ej.data.WebApiAdaptor(),
crossDomain: true
})
});
grid.refresh();
}
function onCheckboxChange(event) {
ej.data.DataUtil.serverTimezoneOffset = checkbox.checked ? 0 : selectedTimezone;
grid.setProperties({
dataSource: new ej.data.DataManager({
url: "https://localhost:****/api/orders", // Replace **** with your actual port number.
adaptor: new ej.data.WebApiAdaptor(),
crossDomain: true
})
});
grid.refresh();
}
</script>
public IActionResult Index()
{
// Timezone List for Dropdown.
List<TimeZoneData> timeZones = new List<TimeZoneData>
{
new TimeZoneData { Value = -12, Text = "-12:00 UTC" },
new TimeZoneData { Value = -11, Text = "-11:00 UTC" },
new TimeZoneData { Value = -10, Text = "-10:00 UTC" },
new TimeZoneData { Value = -9, Text = "-09:00 UTC" },
new TimeZoneData { Value = -8, Text = "-08:00 UTC" },
new TimeZoneData { Value = -7, Text = "-07:00 UTC" },
new TimeZoneData { Value = -6, Text = "-06:00 UTC" },
new TimeZoneData { Value = -5, Text = "-05:00 UTC" },
new TimeZoneData { Value = -4, Text = "-04:00 UTC" },
new TimeZoneData { Value = -3, Text = "-03:00 UTC" },
new TimeZoneData { Value = -2, Text = "-02:00 UTC" },
new TimeZoneData { Value = -1, Text = "-01:00 UTC" },
new TimeZoneData { Value = 0, Text = "+00:00 UTC" },
new TimeZoneData { Value = 1, Text = "+01:00 UTC" },
new TimeZoneData { Value = 2, Text = "+02:00 UTC" },
new TimeZoneData { Value = 3, Text = "+03:00 UTC" },
new TimeZoneData { Value = 4, Text = "+04:00 UTC" },
new TimeZoneData { Value = 5, Text = "+05:00 UTC" },
new TimeZoneData { Value = 5.5, Text = "+05:30 UTC" },
new TimeZoneData { Value = 6, Text = "+06:00 UTC" },
new TimeZoneData { Value = 7, Text = "+07:00 UTC" },
new TimeZoneData { Value = 8, Text = "+08:00 UTC" },
new TimeZoneData { Value = 9, Text = "+09:00 UTC" },
new TimeZoneData { Value = 10, Text = "+10:00 UTC" },
new TimeZoneData { Value = 11, Text = "+11:00 UTC" },
new TimeZoneData { Value = 12, Text = "+12:00 UTC" },
new TimeZoneData { Value = 13, Text = "+13:00 UTC" },
new TimeZoneData { Value = 14, Text = "+14:00 UTC" }
};
ViewBag.TimeZones = timeZones;
return View();
}
How to set custom headers using a custom adaptor in Syncfusion ASP.NET MVC Grid
Custom headers in HTTP requests are used to send additional information such as authentication tokens, API keys, or metadata required by the server. These headers improve security and enable better control over data communication. In the Syncfusion ASP.NET MVC Grid, custom headers can be added when making API requests, ensuring that each request carries the necessary information for server-side validation and processing.
This method is particularly useful when integrating the Grid with authenticated APIs, where requests must include authorization tokens or other security credentials to ensure secure access.
To achieve this, the WebApiAdaptor
can be extended to create the custom adaptor. The beforeSend
method in the custom adaptor allows modifying request headers before sending them to the server. This ensures that every request from the Grid includes the required headers.
The following example demonstrates how to set custom headers using the custom adaptor in Syncfusion ASP.NET MVC Grid.
@Html.EJS().Grid("CustomAdaptor").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("100").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("160").Add();
col.Field("EmployeeID").HeaderText("Employee ID").Width("100").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("150").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().Created("created").Render()
<script>
function created(args) {
class CustomAdaptor extends ej.data.WebApiAdaptor {
beforeSend(args, xhr, settings) {
xhr.withCredentials = true;
super.beforeSend(args, xhr, settings);
xhr.headers.set('Syncfusion', true); // Assign custom headers here.
}
}
var grid = document.querySelector('#CustomAdaptor').ej2_instances[0];
grid.dataSource = new ej.data.DataManager({
url: "https://services.syncfusion.com/js/production/api/orders",
adaptor: new CustomAdaptor()
});
}
</script>
public IActionResult Index()
{
return View();
}
Troubleshoot: Syncfusion ASP.NET MVC Grid render rows without data
In ASP.NET MVC, by default the JSON results are returned in camelCase format. So Grid field names are also changed in camelCase.
To avoid this problem, you need to add DefaultContractResolver in Startup.cs file.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
});
}
``` }