Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added demo datagrid save settings to url #1111

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Radzen.Blazor/RadzenDataGrid.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1970,7 +1970,7 @@ internal override async Task ReloadOnFirstRender()
{
await InvokeLoadData(skip, PageSize);
}
else
else if (settings == null)
{
await base.ReloadOnFirstRender();
}
Expand Down
167 changes: 167 additions & 0 deletions RadzenBlazorDemos/Pages/DataGridSaveSettingUrlLoadData.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
@using Radzen
@using RadzenBlazorDemos.Data
@using RadzenBlazorDemos.Models.Northwind
@using Microsoft.EntityFrameworkCore
@using RadzenBlazorDemos.Services
@using Microsoft.JSInterop

@using System.Text.Json
@using System.Linq.Dynamic.Core
@using System.Text.Json.Serialization
@using System.Web

@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager

@inherits DbContextPage

<p>This example shows how to save/load DataGrid state using Settings property when binding using LoadData event.</p>
<p>Settings is converted to json, encoded in base64 and passed to the current URL as a query parameter</p>
<p>The state includes current page index, page size, groups and columns filter, sort, order, width and visibility.</p>
<RadzenButton Click="@(args => Settings = null)" Text="Clear saved settings" Style="margin-bottom: 16px" />
<RadzenButton Click="@(args => NavigationManager.NavigateTo(NavigationManager.Uri, true))" Text="Reload" Style="margin-bottom: 16px" />
<RadzenDataGrid @ref=grid @bind-Settings="@Settings" AllowFiltering="true" AllowColumnPicking="true" AllowGrouping="true" AllowPaging="true" PageSize="4"
AllowSorting="true" AllowMultiColumnSorting="true" ShowMultiColumnSortingIndex="true"
AllowColumnResize="true" AllowColumnReorder="true" ColumnWidth="200px"
FilterPopupRenderMode="PopupRenderMode.OnDemand" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
Data="@employees" IsLoading=@isLoading Count="@count" LoadData=@LoadData TItem="Employee">
<Columns>
<RadzenDataGridColumn TItem="Employee" Property="Photo" Title="Employee" Sortable="false" Filterable="false">
<Template Context="data">
<RadzenImage Path="@data.Photo" style="width: 40px; height: 40px; border-radius: 8px; margin-right: 8px;" />
@data.FirstName @data.LastName
</Template>
</RadzenDataGridColumn>
<RadzenDataGridColumn TItem="Employee" Property="Title" Title="Title" />
<RadzenDataGridColumn TItem="Employee" Property="EmployeeID" Title="Employee ID" />
<RadzenDataGridColumn TItem="Employee" Property="HireDate" Title="Hire Date" FormatString="{0:d}" />
<RadzenDataGridColumn TItem="Employee" Property="City" Title="City" />
<RadzenDataGridColumn TItem="Employee" Property="Country" Title="Country" />
</Columns>
</RadzenDataGrid>

<EventConsole @ref=@console />

@code {
RadzenDataGrid<Employee> grid;
IEnumerable<Employee> employees;
EventConsole console;

int count;
bool isLoading = false;
bool loaded;
async Task LoadData(LoadDataArgs args)
{
console.Log("LoadData");
isLoading = true;

await Task.Yield();

var query = dbContext.Employees.AsQueryable();

if (!string.IsNullOrEmpty(args.Filter))
{
query = query.Where(args.Filter);
}

if (!string.IsNullOrEmpty(args.OrderBy))
{
query = query.OrderBy(args.OrderBy);
}

count = query.Count();

// Simulate async data loading
await Task.Delay(2000);

employees = await Task.FromResult(query.Skip(args.Skip.Value).Take(args.Top.Value).ToList());

isLoading = false;

loaded = true;
}

DataGridSettings _settings;
public DataGridSettings Settings
{
get
{
return _settings;
}
set
{
if (_settings != value)
{
_settings = value;
console.Log("Set");
InvokeAsync(SaveStateAsync);
}
}
}

//json settings to reduce string length
private static JsonSerializerOptions _jsonOptions = new()
{
// Specify the condition to ignore properties when writing null or default values
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull & JsonIgnoreCondition.WhenWritingDefault,

// Use UnsafeRelaxedJsonEscaping to allow special characters in the JSON string
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,

// Set WriteIndented to false to remove indentation from the JSON string
WriteIndented = false,

// Ignore read-only properties during serialization
IgnoreReadOnlyProperties = true
};

private void LoadStateAsync()
{
// Get the absolute URI and parse the query strings
var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
var queryStrings = HttpUtility.ParseQueryString(uri.Query);

// Retrieve the "query" parameter from the query strings
var settingsJson = queryStrings["query"];

// Check if the "settingsJson" parameter is not null or empty
if (!string.IsNullOrEmpty(settingsJson))
{
// Convert the base64 encoded string to compressed bytes
byte[] compressedBytes = Convert.FromBase64String(settingsJson);

// Deserialize the compressed bytes to a DataGridSettings object using the specified JsonSerializerOptions
_settings = JsonSerializer.Deserialize<DataGridSettings>(compressedBytes, _jsonOptions);
}
}

private void SaveStateAsync()
{
console.Log("SaveStateAsync");

var uri = new Uri(NavigationManager.Uri);
string url = $"{uri.AbsolutePath}";

if (Settings != null)
{
// Serialize the Settings object to UTF-8 encoded bytes using the specified JsonSerializerOptions
var bytes = JsonSerializer.SerializeToUtf8Bytes(Settings, _jsonOptions);

// Convert the bytes to a base64 encoded string
string settingsJson = Convert.ToBase64String(bytes);

// Escape the base64 encoded string to make it URL-safe
settingsJson = Uri.EscapeDataString(settingsJson);

// Append the "query" parameter to the URL with the escaped settingsJson
url += $"?query={settingsJson}";
}
NavigationManager.NavigateTo(url);
}

protected override void OnInitialized()
{
LoadStateAsync();
base.OnInitialized();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
@page "/datagrid-save-settings-url-loaddata"

<RadzenText TextStyle="TextStyle.H2" TagName="TagName.H1" class="rz-pt-8">
DataGrid <strong>save settings</strong> to URL query using LoadData binding
</RadzenText>

<RadzenExample ComponentName="DataGrid" Example="DataGridSaveSettingUrlLoadData">
<DataGridSaveSettingUrlLoadData />
</RadzenExample>
2 changes: 1 addition & 1 deletion RadzenBlazorDemos/Pages/DataGridSaveSettingsLoadData.razor
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<p>This example shows how to save/load DataGrid state using Settings property when binding using LoadData event.</p>
<p>The state includes current page index, page size, groups and columns filter, sort, order, width and visibility.</p>
<RadzenButton Click="@(args => Settings = null)" Text="Clear saved settings" Style="margin-bottom: 16px" />
<RadzenButton Click="@(args => NavigationManager.NavigateTo("/datagrid-save-settings", true))" Text="Reload" Style="margin-bottom: 16px" />
<RadzenButton Click="@(args => NavigationManager.NavigateTo("/datagrid-save-settings-loaddata", true))" Text="Reload" Style="margin-bottom: 16px" />
<RadzenDataGrid @ref=grid @bind-Settings="@Settings" AllowFiltering="true" AllowColumnPicking="true" AllowGrouping="true" AllowPaging="true" PageSize="4"
AllowSorting="true" AllowMultiColumnSorting="true" ShowMultiColumnSortingIndex="true"
AllowColumnResize="true" AllowColumnReorder="true" ColumnWidth="200px"
Expand Down
8 changes: 8 additions & 0 deletions RadzenBlazorDemos/Services/ExampleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,14 @@ public class ExampleService
Path = "datagrid-save-settings-loaddata",
Title = "Blazor DataGrid save/load settings with LoadData",
Tags = new [] { "save", "load", "settings", "async", "loaddata" }
},
new Example()
{
New = true,
Name = "URL query parameter",
Path = "datagrid-save-settings-url-loaddata",
Title = "Blazor DataGrid save/load settings with URL query parameter",
Tags = new [] { "save", "load", "settings", "async", "loaddata", "url", "query" }
}
}
},
Expand Down
Loading