Enhance User Experience: Preserve ASP.NET Core Grid Layout Settings
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (180).NET Core  (28).NET MAUI  (224)Angular  (113)ASP.NET  (49)ASP.NET Core  (81)ASP.NET MVC  (87)Azure  (41)Black Friday Deal  (1)Blazor  (234)BoldSign  (14)DocIO  (24)Essential JS 2  (110)Essential Studio  (199)File Formats  (72)Flutter  (135)JavaScript  (226)Microsoft  (121)PDF  (83)Python  (1)React  (105)Streamlit  (1)Succinctly series  (131)Syncfusion  (960)TypeScript  (33)Uno Platform  (3)UWP  (3)Vue  (46)Webinar  (53)Windows Forms  (59)WinUI  (72)WPF  (162)Xamarin  (159)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (10)Business intelligence  (55)Button  (4)C#  (163)Chart  (145)Chart of the week  (57)Cloud  (15)Company  (440)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (73)Development  (676)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (7)Essential Tools  (13)Excel  (43)Extensions  (23)File Manager  (7)Gantt  (20)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (519)Mobile MVC  (9)OLAP server  (2)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (45)Performance  (13)PHP  (2)PivotGrid  (5)Predictive Analytics  (6)Report Server  (3)Reporting  (8)Reporting / Back Office  (9)Rich Text Editor  (12)Road Map  (12)Scheduler  (54)Security  (5)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (32)Solution Services  (4)Spreadsheet  (11)SQL  (15)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (113)UI  (400)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (624)What's new  (337)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Enhance User Experience: Preserve ASP.NET Core Grid Layout Settings

Enhance User Experience: Preserve ASP.NET Core Grid Layout Settings

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:

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.

P reserving ASP.NET Core DataGrid layout settings
Preserving ASP.NET Core DataGrid layout settings

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 forumssupport portal, or feedback portal. We’re always eager to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed