Skip to content

Commit 9d08ef4

Browse files
docs(grid): initial state, alter the state - examples
1 parent c0a39db commit 9d08ef4

File tree

6 files changed

+157
-0
lines changed

6 files changed

+157
-0
lines changed

_contentTemplates/grid/state.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
#initial-state
2+
>tip If you want to set an initial state to the grid, use a similar snippet, but in the [`OnStateInit event`]({%slug grid-state%}#set-default-initial-state)
3+
#end
4+
5+
16
#set-sort-from-code
27
@* This snippet shows how to set sorting state to the grid from your code *@
38

components/grid/filtering.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ A key difference in the behavior from the [filter row](#filter-row) is that the
155155

156156
You can set the grid filters from your code through the grid [state]({%slug grid-state%}).
157157

158+
@[template](/_contentTemplates/grid/state.md#initial-state)
159+
158160
>caption Set sorting programmatically
159161
160162
````FilterRow

components/grid/grouping.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ Drag the column header of the "Team" and/or "On Vacation" column to the group pa
8080

8181
You can set the grid grouping from your code through the grid [state]({%slug grid-state%}). You can define the list of fields by which the grid is grouped and indexes of groups that will be collapsed (all groups are expanded by default).
8282

83+
@[template](/_contentTemplates/grid/state.md#initial-state)
84+
8385
>caption Set grouping programmatically
8486
8587
````CSHTML

components/grid/hierarchy.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ Click the + icon to expand the row details
9292

9393
You can choose which detail templates will be expanded from your code through the grid [state]({%slug grid-state%}) by their indexes (all detail templates are collapsed by default).
9494

95+
@[template](/_contentTemplates/grid/state.md#initial-state)
96+
9597
>caption Expand DetailTemplate hierarchy from code
9698
9799
````CSHTML

components/grid/sorting.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ You can sort this grid on the different columns to see the results. The `Name` c
5353

5454
You can sort the grid from your own code through its [state]({%slug grid-state%}).
5555

56+
@[template](/_contentTemplates/grid/state.md#initial-state)
57+
5658
>caption Set sorting programmatically
5759
5860
````CSHTML

components/grid/state.md

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,23 @@ You can see this feature in the [Live Demo: Grid State](https://demos.telerik.co
1616

1717
This article contains the following sections:
1818

19+
<!-- Start Document Outline -->
20+
1921
* [Basics](#basics)
2022
* [Events](#events)
2123
* [Methods](#methods)
2224
* [Information in the Grid State](#information-in-the-grid-state)
2325
* [Examples](#examples)
2426
* [Save and Load Grid State from Browser LocalStorage](#save-and-load-grid-state-from-browser-localstorage)
2527
* [Set Grid Options Through State](#set-grid-options-through-state)
28+
* [Set Default (Initial) State](#set-default-initial-state)
29+
* [Get and Override User Action That Changes The Grid](#get-and-override-user-action-that-changes-the-grid)
2630
* [Initiate Editing or Inserting of an Item](#initiate-editing-or-inserting-of-an-item)
2731

2832

33+
<!-- End Document Outline -->
34+
35+
2936
## Basics
3037

3138
The grid state is a generic class whose type is determined by the type of the model you use for the grid. It contains fields that correspond to the grid behaviors which you can use to save, load and modify the grid state.
@@ -282,6 +289,9 @@ The grid state allows you to control the behavior of the grid programmatically -
282289

283290
>tip The individual tabs below show how you can use the state to programmatically set the grid filtering, sorting, grouping and other features.
284291
292+
@[template](/_contentTemplates/grid/state.md#initial-state)
293+
294+
285295
````Sorting
286296
@[template](/_contentTemplates/grid/state.md#set-sort-from-code)
287297
````
@@ -298,6 +308,140 @@ The grid state allows you to control the behavior of the grid programmatically -
298308
@[template](/_contentTemplates/grid/state.md#expand-hierarchy-from-code)
299309
````
300310

311+
### Set Default (Initial) State
312+
313+
If you want the grid to start with certain settings for your end users, you can pre-define them in the `OnStateInit event`.
314+
315+
>caption Choose a default state of the grid for your users
316+
317+
````CSHTML
318+
@* Set default (initial) state of the grid
319+
In this example, the records with ID < 5 will be shown, and the Name field will be sorted descending *@
320+
321+
<TelerikGrid Data="@MyData" Sortable="true" FilterMode="@GridFilterMode.FilterRow" AutoGenerateColumns="true"
322+
OnStateInit="@((GridStateEventArgs<SampleData> args) => OnStateInitHandler(args))">
323+
</TelerikGrid>
324+
325+
@code {
326+
async Task OnStateInitHandler(GridStateEventArgs<SampleData> args)
327+
{
328+
var state = new GridState<SampleData>
329+
{
330+
SortDescriptors = new List<Telerik.DataSource.SortDescriptor>
331+
{
332+
new Telerik.DataSource.SortDescriptor{ Member = "Name", SortDirection = Telerik.DataSource.ListSortDirection.Descending }
333+
},
334+
FilterDescriptors = new List<Telerik.DataSource.FilterDescriptorBase>()
335+
{
336+
new Telerik.DataSource.FilterDescriptor() { Member = "Id", Operator = Telerik.DataSource.FilterOperator.IsLessThan, Value = 5, MemberType = typeof(int) },
337+
}
338+
};
339+
340+
args.GridState = state;
341+
}
342+
343+
public IEnumerable<SampleData> MyData = Enumerable.Range(1, 30).Select(x => new SampleData
344+
{
345+
Id = x,
346+
Name = "name " + x,
347+
Team = "team " + x % 5,
348+
HireDate = DateTime.Now.AddDays(-x).Date
349+
});
350+
351+
public class SampleData
352+
{
353+
public int Id { get; set; }
354+
public string Name { get; set; }
355+
public string Team { get; set; }
356+
public DateTime HireDate { get; set; }
357+
}
358+
}
359+
````
360+
361+
### Get and Override User Action That Changes The Grid
362+
363+
Sometimes you may want to know what the user changed in the grid (e.g., when they filter, sort and so on) and even override those operations. One way to do that is to monitor the [`OnRead`]({%slug components/grid/manual-operations%}#cache-data-request) event, cache the previous `DataSourceRequest`, compare against it, alter it if needed, and implement the operations yourself. Another is to use the `OnStateChanged` event.
364+
365+
The example below shows the latter. Review the code comments to see how it works and to make sure you don't get issues.
366+
367+
>caption Know when the grid state changes, which parameter changes, and amend the change
368+
369+
````CSHTML
370+
@* This example does the following:
371+
* Logs to the console what changed in the grid
372+
* If the user changes the Name column filtering, the filter is always overriden to "Contains" and its value to "name 1"
373+
* if there is no filter on the ID column, the ID column is filtered with ID < 15.
374+
To test it out, try filtering the name column
375+
*@
376+
377+
@using Telerik.DataSource
378+
379+
<TelerikGrid Data="@MyData" Sortable="true" FilterMode="@GridFilterMode.FilterRow" AutoGenerateColumns="true" Pageable="true"
380+
OnStateChanged="@((GridStateEventArgs<SampleData> args) => OnStateChangedHandler(args))" @ref="GridRef">
381+
</TelerikGrid>
382+
383+
@code {
384+
TelerikGrid<SampleData> GridRef { get; set; }
385+
386+
// Note: This can cause a performance delay if you do long operations here
387+
// Note 2: The grid does not await this event, its purpose is to notify you of changes
388+
// so you must not perform async operations and data loading here, or issues with the grid state may occur
389+
// or other things you change on the page won't actually change. The .SetState() call redraws only the grid, but not the rest of the page
390+
async void OnStateChangedHandler(GridStateEventArgs<SampleData> args)
391+
{
392+
Console.WriteLine(args.PropertyName); // get the setting that was just changed (paging, sorting,...)
393+
394+
if (args.PropertyName == "FilterDescriptors") // sorting changed for our example
395+
{
396+
// ensure certain state based on some condition
397+
// in this example - ensure that the ID field is always filtered with a certain setting unless the user filters it explicitly
398+
bool isIdFiltered = false;
399+
foreach (FilterDescriptor item in args.GridState.FilterDescriptors)
400+
{
401+
if(item.Member == "Id")
402+
{
403+
isIdFiltered = true;
404+
}
405+
406+
// you could override a user action as well - change settings on the corresponding parameter
407+
// make sure that the .SetState() method of the grid is always called if you do that
408+
if(item.Member == "Name")
409+
{
410+
item.Value = "name 1";
411+
item.Operator = FilterOperator.Contains;
412+
}
413+
}
414+
if (!isIdFiltered)
415+
{
416+
args.GridState.FilterDescriptors.Add(new FilterDescriptor
417+
{
418+
Member = "Id", MemberType = typeof (int), Operator = FilterOperator.IsLessThan, Value = 15
419+
});
420+
}
421+
// needed only if you will be overriding user actions or amending them
422+
// if you only need to be notified of changes, you should not call this method
423+
await GridRef.SetState(args.GridState);
424+
}
425+
}
426+
427+
public IEnumerable<SampleData> MyData = Enumerable.Range(1, 300).Select(x => new SampleData
428+
{
429+
Id = x,
430+
Name = "name " + x,
431+
Team = "team " + x % 5,
432+
HireDate = DateTime.Now.AddDays(-x).Date
433+
});
434+
435+
public class SampleData
436+
{
437+
public int Id { get; set; }
438+
public string Name { get; set; }
439+
public string Team { get; set; }
440+
public DateTime HireDate { get; set; }
441+
}
442+
}
443+
````
444+
301445
### Initiate Editing or Inserting of an Item
302446

303447
The grid state lets you store the item that the user is currently working on - both an existing model that is being edited, and a new item the user is inserting. This happens automatically when you save the grid state. If you want to save on every keystroke instead of on `OnChange` - use a custom editor template and update the `EditItem` or `InsertedItem` of the state object as required, then save the state into your service.

0 commit comments

Comments
 (0)