TL;DR: Once again, are you frustrated when refreshing the app and losing your settings? Syncfusion ASP.NET Core DataGrid easily preserves and restores user preferences like column order, width, and sorting. This guide covers setting up an ASP.NET Core project, configuring DataGrid, and managing grid states with server-side storage.
Preserving and restoring layout configurations is pivotal in delivering a smooth and intuitive user experience in the ever-evolving web development landscape. Today, we embark on an in-depth journey to achieve that goal in our Syncfusion ASP.NET Core DataGrid.
This guide will delve into the intricacies of utilizing server-side mechanisms to efficiently manage and persist the grid’s state across various interactions and sessions. We’ll unveil the seamless fusion of server-side processing with client-side interactions, facilitating enhanced performance and usability for DataGrid implementations.
Enhancing user experience: Storing and restoring configurations
Efficiency and convenience take center stage as we discuss how storing grid layout configurations, including column order, width, visibility, sorting, and more, can significantly enhance the user experience. By enabling users to retain their customized settings across sessions, we eliminate the need for repetitive configuration, fostering a smoother and more user-friendly interface.
Prerequisites
Before diving into the implementation details, ensure that your system meets the requirements for ASP.NET Core components.
Creating an ASP.NET Core web app with Razor pages
Follow the steps to create an ASP.NET Core web app using Razor pages:
- Utilize Microsoft Templates to initiate your project.
- Incorporate Syncfusion ASP.NET Core Extension into your project setup.
Getting started with ASP.NET Core DataGrid
Refer to the getting started documentation for a comprehensive guide on initiating your journey with the ASP.NET Core DataGrid.
Step-by-step guide to preserve ASP.NET Core DataGrid layout settings
In the following example, we will meticulously outline the process of persisting essential features and their outcomes following user interactions with the grid layout. These features include:
- Filtering
- Sorting
- Grouping
- Paging
- Column chooser (Show/Hide Columns)
Defining the initial DataGrid configuration
To begin configuring the Syncfusion ASP.NET Core DataGrid, navigate to the Index.cshtml file. Here, we outline the foundational steps for setting up and preserving various grid features.
Refer to the following code example.
<div> <ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="500" created="created" allowFiltering="true" allowGrouping="true" allowSorting="true" allowPaging="true" showColumnChooser="true" enablePersistence="true" toolbar="@(new List<string>() { "ColumnChooser"})"> <e-grid-columns> <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" 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="170"></e-grid-column> <e-grid-column field="Freight" headerText="Freight" format="c2" width="170"></e-grid-column> <e-grid-column field="ShipCity" headerText="Ship City" width="170"></e-grid-column> <e-grid-column field="ShipCountry" headerText="Ship Country" width="170"></e-grid-column> </e-grid-columns> </ejs-grid> </div>
In the provided code snippet, we have initialized the grid component and configured its essential attributes, such as data source, height, and various interactive functionalities like filtering, grouping, sorting, and paging. Additionally, we have defined columns with specific fields and headers to structure the grid’s content effectively.
Let’s implement an event called created to preserve the grid’s initial state before user interactions. This event captures and stores the grid’s initial configuration in the local storage.
<script> var grid; function created() { grid = this; window.localStorage.setItem('initialGrid', grid.getPersistData()); // Store the initial grid state to local storage on initial rendering. } </script>
Defining data model and data source
In the HomeController.cs file, we will establish the data model (OrdersDetails) and data source (GetAllRecords) for the DataGrid. Then, we’ll retrieve records using the OrdersDetails.GetAllRecords() method and store them in ViewBag.DataSource, thereby enabling its utilization as local data on the client side.
public IActionResult Index() { var Order = OrdersDetails.GetAllRecords(); ViewBag.DataSource = Order; return View(); } public class OrdersDetails { public static List<OrdersDetails> order = new List<OrdersDetails>(); public OrdersDetails() { } public OrdersDetails(int OrderID, string CustomerId, int EmployeeId, double Freight, string ShipCity, string ShipCountry) { this.OrderID = OrderID; this.CustomerID = CustomerId; this.EmployeeID = EmployeeId; this.Freight = Freight; this.ShipCity = ShipCity; this.ShipCountry = ShipCountry; } public static List<OrdersDetails> GetAllRecords() { if (order.Count() == 0) { int code = 10000; for (int i = 1; i < 5; i++) { order.Add(new OrdersDetails(code + 1, "ALFKI", i + 0, 0, "Berlin", "Denmark")); order.Add(new OrdersDetails(code + 2, "ANATR", i + 2, 3.3 * i, "Madrid", "Brazil")); order.Add(new OrdersDetails(code + 3, "ANTON", i + 1, 0, "Cholchester", "Germany")); order.Add(new OrdersDetails(code + 4, "BLONP", i + 3, 5.3 * i, "Marseille", "Austria")); order.Add(new OrdersDetails(code + 5, "BOLID", i + 4, 6.3 * i, "Tsawassen", "Switzerland")); code += 5; } } return order; } 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 string ShipCountry { get; set; } }
Creating separate buttons for layout persistence actions
Here, we will use the Syncfusion ASP.NET Core Button component to render buttons for storing, restoring, and resetting layout persistence actions.
<ejs-button id="storestate" cssClass="e-flat" isPrimary="true" content="Store State"></ejs-button> <ejs-button id="reset" cssClass="e-flat" content="Reset"></ejs-button> <ejs-button id="restorestate" cssClass="e-flat" content="Restore State"></ejs-button>
Managing store action on the client side
In the script section of the Index.cshtml file, we’ll utilize addEventListener to handle store actions. Upon clicking the storestate button, it retrieves persisted data from the grid via the getPersistData() method and sends it to the server using an EJ2 AJAX POST request.
Refer to the following code example.
document.getElementById("storestate").addEventListener('click', function () { // Get the persisted data from the grid using the getPersistData method. var persistData = JSON.stringify({ persistData: grid.getPersistData() }) var ajax = new ej.base.Ajax({ // Used EJ2 ajax to send the stored persistData to the server. url: "/Home/StorePersistData", type: "POST", contentType: "application/json; charset=utf-8", datatype: "json", data: persistData // Send the data to the server. }); ajax.send(); });
Restoration actions on the client side
Within the script section of the Index.cshtml file, incorporate addEventListener to manage restoration actions. Upon clicking the restorestate button, the script will fetch persisted data from the server and then seamlessly integrate it into the grid by employing the setProperties() method.
Refer to the following code example.
document.getElementById("restorestate").addEventListener('click', function () { var ajax = new ej.base.Ajax({ // Used EJ2 ajax to retrieve the persist data from the server. url: "/Home/Restore", type: "POST", contentType: "application/json; charset=utf-8" }); ajax.send(); ajax.onSuccess = function (result) { var state = JSON.parse(result); // Get the data. grid.setProperties(state); // Restore the Grid state. } });
Reset actions on the client side
In the Index.cshtml file’s script section, include the onClick event to manage the reset action. When the reset button is clicked, it fetches the initial grid persisted data from the local storage and applies it to the grid using the setProperties() method.
Refer to the following code example.
document.getElementById('reset').onclick = function () { var savedProperties = JSON.parse(window.localStorage.getItem('initialGrid')); // Get the initial grid state from local storage. grid.setProperties(savedProperties)// Reset the grid to the initial state. }
Server-side implementation of storage and restoration actions
In the HomeController.cs file, establish the server-side actions for managing the storage and restoration of the grid’s persisted data. The StorePersistData action is responsible for receiving data from the client and storing it in a static variable. Conversely, the Restore action merely returns the stored data.
Refer to the following code example.
public static string? persistedData; public IActionResult StorePersistData([FromBody] StoreData persistData) { persistedData = persistData.persistData; // You can store this in the database. return new JsonResult(persistedData); } public IActionResult Restore() { return Content(persistedData); // Retrieve the stored layout from the database. }
Refer to the following output image.
GitHub reference
Refer to the preserving ASP.NET Core DataGrid layout settings demo on GitHub for more
Conclusion
Thanks for reading this blog! We have comprehensively explored how to preserve Syncfusion’s ASP.NET Core DataGrid layout. This powerful technique enhances user experiences and empowers users to maintain personalized preferences across sessions. Try out the steps in this blog and share your feedback in the comment section below.
Alternatively, you can contact us through our support forums, support portal, or feedback portal. We’re always eager to assist you!