Skip to main content

Manage Dashboard State in ASP.NET Core Applications

  • 7 minutes to read

The dashboard state stores the state of individual dashboard items and dashboard parameter values. It can be master filter and drill-down values, active tab page, selected parameter values, and other results of user actions in a dashboard on the client.

Manage the Dashboard State on the Server

Dashboard State Object

On the server, the dashboard state is stored in a DashboardState class instance:

DashboardState dashboardState = new DashboardState();

DashboardParameterState parameterState = 
    new DashboardParameterState("countryParameter", "USA", typeof(string));

DashboardItemState treemapDrilldownState = new DashboardItemState("treemapDashboardItem1");
treemapDrilldownState.DrillDownValues.Add("Beverages");

DashboardItemState rangeFilterState = new DashboardItemState("rangeFilterDashboardItem1");
rangeFilterState.RangeFilterState.Selection = 
    new RangeFilterSelection(new DateTime(2015, 1, 1), new DateTime(2016, 1, 1));

dashboardState.Parameters.Add(parameterState);
dashboardState.Items.AddRange(new List<DashboardItemState>() {
    treemapDrilldownState,
    rangeFilterState }
);

States of Individual Dashboard Items

Use the DashboardState.Items property to access the state of individual dashboard items:

DashboardItemState.MasterFilterValues
Gets or sets selected master filter values stored in a dashboard state.
DashboardItemState.DrillDownValues.DrillDownValues
Gets or sets values for the drill-down hierarchy.
DashboardItemState.TabPageName
Gets the name of the tab page to which the dashboard item belongs.
DashboardItemState.RangeFilterState
Gets or sets the state of the Range Filter and Date Filter dashboard items.
DashboardItemState.SelectedLayerIndex
Gets or sets an index of the selected dashboard item layer.

Dashboard Parameter Values

Use the DashboardState.Parameters property to access the selected dashboard parameter values.

Manage a Dashboard State

You can use the following API to apply a DashboardState on the server:

DashboardBuilder.InitialDashboardState
Specifies the initial state of the loaded dashboard.
DashboardConfigurator.SetDashboardStateService
Specifies a service that allows you to manage a dashboard state.

See the Examples section for implementation details.

Add a Dashboard State to a URL

Users can share a dashboard state by appending this state to the URL of the currently browsed dashboard. Enable the DashboardUrlStateOptionBuilder.IncludeDashboardStateToUrl method to display the state information in the URL. In this case, users can share a link to the dashboard with the applied state.

<div style="position: absolute; left:0;top:0;right:0;bottom:0;">
    @(Html.DevExpress().Dashboard("clientDashboard1")
        .Width("100%")
        .Height("100%")
        .WorkingMode(WorkingMode.Viewer)
        .Extensions(extension => extension.UrlState(state => state.IncludeDashboardStateToUrl(true)))
    )    
</div>

You can also add the identifier of the selected dashboard to the URL. For this, set the DashboardUrlStateOptionBuilder.IncludeDashboardIdToUrl method to true.

Note

These properties are in effect when the DashboardBuilder.WorkingMode is set to WorkingMode.Viewer or WorkingMode.ViewerOnly.

Apply a Dashboard State during Server-Side Export

You can use the AspNetCoreDashboardExporter to apply a dashboard state during the server-side export. For this, use the overload of the following methods with the dashboardState parameter:

For more information, see Manage Exporting Capabilities.

Manage a Dashboard State on the Client

Dashboard State Object

On the client, the dashboard state stores the same data: the state of individual dashboard items and dashboard parameter values. You can use the state as a JSON string or as a DashboardState object:

function setStateAsString() {
    var currentState = `{"Items":{"listBoxDashboardItem1":{"MasterFilterValues":[["Beverages"]]},
            "tabContainerDashboardItem1":{"TabPageName":"dashboardTabPage2"},
            "cardDashboardItem1":{"SelectedLayerIndex":1}}}`

    dashboardControl.GetDashboardControl().setDashboardState(currentState);
}
function setStateAsObject() {
  dashboardControl.GetDashboardControl().setDashboardState({
    "Parameters": {
      "Year": 2008
    },
    "Items": {
      "cardProductionImportByType": {
          MasterFilterValues: [["Solid Fuels"]]
      }
    }
  });
}

States of Individual Dashboard Items

On the client, use the DashboardState.Items property to access the dashboard item’s state:

ItemState.MasterFilterValues
Specifies the selected master filter values stored in a dashboard state.
ItemState.DrillDownValues
Specifies the current drill-down values.
ItemState.TabPageName
Specifies the name of the selected tab page in the Tab Container.
ItemState.RangeFilterState
Specifies the state of the Range Filter and Date Filter dashboard items.
ItemState.SelectedLayerIndex
Specifies the index of the selected dashboard item layer for the Pie, Card, Treemap, Gauge, and Choropleth Map dashboard items.

Dashboard Parameter Values

Use the DashboardState.Parameters property to get access to the selected value of the dashboard parameters.

Manage a Dashboard State

You can use the following API to apply the DashboardState on the client:

DashboardControlOptions.initialDashboardState
Specifies the initial state of the loaded dashboard.
DashboardControl.getDashboardState
Gets the current dashboard state.
DashboardControl.setDashboardState
Applies the dashboard state to the loaded dashboard.

The DashboardControlOptions.onDashboardStateChanged event occurs after the current dashboard state changes in the Web Dashboard. You can use this event to update the dashboard state value.

See the Examples section for implementation details.

Client-Server Interaction

To initialize the DashboardState object with the JSON object from the client, call the server-side DashboardStateExtensions.LoadFromJson method. Use DashboardStateExtensions.SaveToJson to save the current DashboardState object to JSON. Use the HttpRequest.Cookies property to get a collection of cookies sent by the client.

On the client, the document.cookie property reads and writes cookies associated with the document.

Examples

Example 1: Specify a Default Dashboard State

The sample illustrates how to specify a dashboard state (such as a master filter or parameter values) in code and how to apply this state when loading a dashboard for the first time. In this example, the DashboardState object defined in the Controller stores the dashboard state. The MVC approach is used to pass the specified dashboard state to the View’s DashboardBuilder.InitialDashboardState property and use this state when loading a dashboard.

View Example: ASP.NET Core

@model DevExpress.DashboardCommon.DashboardState
<div style="position: absolute; left:0;top:0;right:0;bottom:0;">
    @(Html.DevExpress().Dashboard("clientDashboardDesigner1")
        .ControllerName("DefaultDashboard")
        .Width("100%")
        .Height("100%")
        .WorkingMode(WorkingMode.Viewer)
        .InitialDashboardState(Model.SaveToJson())
        .Extensions(extension => extension.UrlState(state => state.IncludeDashboardStateToUrl(true)))
    )
</div>

Example 2: Save a Dashboard State to Cookies

The sample illustrates how to save the current ASP.NET Core Dashboard state (such as master filter or parameter values) to cookies on the client side and restore this state on the server side.

View Example: ASP.NET MVC

On the server, create a custom dashboard state service so you can load the dashboard state from the cookies:

using DevExpress.DashboardAspNetCore;
using DevExpress.DashboardCommon;
using DevExpress.DashboardWeb;
using Microsoft.AspNetCore.Http;
using System.Web;
using System.Xml.Linq;

namespace WebDashboardAspNetCore {
    public class CustomDashboardStateService : IDashboardStateService {
        IHttpContextAccessor? contextAccessor;
        public CustomDashboardStateService(IHttpContextAccessor? contextAccessor) {
            this.contextAccessor = contextAccessor;
        }
        public DashboardState? GetState(string dashboardId, XDocument dashboard) {
            var cookie = contextAccessor?.HttpContext?.Request.Cookies["dashboardState"];
            if (cookie != null) {
                DashboardState dashboardState = new DashboardState();
                dashboardState.LoadFromJson(HttpUtility.UrlDecode(cookie));
                return dashboardState;
            } else
                return null;
        }
    }
}

Call the DashboardConfigurator.SetDashboardStateService(IDashboardStateService) method to apply the created dashboard state service:

configurator.SetDashboardStateService(new CustomDashboardStateService(contextAccessor));

Handle the DashboardControlOptions.onBeforeRender event:

<div style="position: absolute; left: 0; top: 0; right: 0; bottom: 0;">
@(Html.DevExpress().Dashboard("dashboardControl1")
    .ControllerName("DefaultDashboard")
    .Width("100%")
    .Height("100%")
    .OnBeforeRender("onBeforeRender")
)
</div>

On the client, the DashboardControlOptions.onDashboardStateChanged event is handled so that the control saves the dashboard state to cookies every time the state changes.

function onBeforeRender(sender) {
    const dashboardControl = sender;
    if (dashboardControl)
        dashboardControl.on('dashboardStateChanged', onDashboardStateChanged);
}

function onDashboardStateChanged(e) {
    // Set the number of days until the cookie should expire (exdays):
    const exdays = 1;
    const date = new Date();
    date.setTime(date.getTime() + (exdays * 24 * 60 * 60 * 1000));
    let expires = "expires=" + date.toUTCString();
    // Get a dashboard state:
    let dState = "dashboardState=" + encodeURIComponent(e.component.getDashboardState()) + ";";
    // Assign the cookie name (dashboardState), the cookie value, and the expires string to document.cookie:
    document.cookie = dState + expires + ";path=" + encodeURIComponent("/");
}

Example 3: Reset a Dashboard State to Default

The code below clears filters (unselects all master filter values), the RangeFilter state and drill-down levels for dashboard items. To do this, assign an empty array of objects to the ItemState.MasterFilterValues, ItemState.DrillDownValues and ItemState.RangeFilterState properties.

function onClick() {
    //...
    var state = JSON.parse(control.getDashboardState());
    if (state && state.Items) {
        Object.keys(state.Items).forEach(function (itemName) {
            var itemState = state.Items[itemName];
            itemState.MasterFilterValues = [];
            itemState.DrillDownValues = [];
            itemState.RangeFilterState = { };
        }) 
    }
    control.setDashboardState(JSON.stringify(state));
}

Note

The control variable is the obtained DashboardControl instance. Refer to the Extensions Overview topic for information on how to obtain a DashboardControl for each platform.