Widgets

ABP provides a model and infrastructure to create reusable widgets. Widget system is an extension to ASP.NET Core’s ViewComponents. Widgets are especially useful when you want to;

  • Have scripts & styles dependencies for your widget.
  • Create dashboards with widgets used inside.
  • Define widgets in reusable modules.
  • Co-operate widgets with authorization and bundling systems.

Basic Widget Definition

Create a View Component

As the first step, create a new regular ASP.NET Core View Component:

widget-basic-files

MySimpleWidgetViewComponent.cs:

  1. using Microsoft.AspNetCore.Mvc;
  2. using Volo.Abp.AspNetCore.Mvc;
  3. namespace DashboardDemo.Web.Pages.Components.MySimpleWidget
  4. {
  5. public class MySimpleWidgetViewComponent : AbpViewComponent
  6. {
  7. public IViewComponentResult Invoke()
  8. {
  9. return View();
  10. }
  11. }
  12. }

Inheriting from AbpViewComponent is not required. You could inherit from ASP.NET Core’s standard ViewComponent. AbpViewComponent only defines some base useful properties.

You can inject a service and use in the Invoke method to get some data from the service. You may need to make Invoke method async, like public async Task<IViewComponentResult> InvokeAsync(). See ASP.NET Core’s ViewComponents document fore all different usages.

Default.cshtml:

  1. <div class="my-simple-widget">
  2. <h2>My Simple Widget</h2>
  3. <p>This is a simple widget!</p>
  4. </div>

Define the Widget

Add a Widget attribute to the MySimpleWidgetViewComponent class to mark this view component as a widget:

  1. using Microsoft.AspNetCore.Mvc;
  2. using Volo.Abp.AspNetCore.Mvc;
  3. using Volo.Abp.AspNetCore.Mvc.UI.Widgets;
  4. namespace DashboardDemo.Web.Pages.Components.MySimpleWidget
  5. {
  6. [Widget]
  7. public class MySimpleWidgetViewComponent : AbpViewComponent
  8. {
  9. public IViewComponentResult Invoke()
  10. {
  11. return View();
  12. }
  13. }
  14. }

Rendering a Widget

Rendering a widget is pretty standard. Use the Component.InvokeAsync method in a razor view/page as you do for any view component. Examples:

  1. @await Component.InvokeAsync("MySimpleWidget")
  2. @await Component.InvokeAsync(typeof(MySimpleWidgetViewComponent))

First approach uses the widget name while second approach uses the view component type.

Widgets with Arguments

ASP.NET Core’s view component system allows you to accept arguments for view components. The sample view component below accepts startDate and endDate and uses these arguments to retrieve data from a service.

  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Volo.Abp.AspNetCore.Mvc;
  5. using Volo.Abp.AspNetCore.Mvc.UI.Widgets;
  6. namespace DashboardDemo.Web.Pages.Shared.Components.CountersWidget
  7. {
  8. [Widget]
  9. public class CountersWidgetViewComponent : AbpViewComponent
  10. {
  11. private readonly IDashboardAppService _dashboardAppService;
  12. public CountersWidgetViewComponent(IDashboardAppService dashboardAppService)
  13. {
  14. _dashboardAppService = dashboardAppService;
  15. }
  16. public async Task<IViewComponentResult> InvokeAsync(
  17. DateTime startDate, DateTime endDate)
  18. {
  19. var result = await _dashboardAppService.GetCountersWidgetAsync(
  20. new CountersWidgetInputDto
  21. {
  22. StartDate = startDate,
  23. EndDate = endDate
  24. }
  25. );
  26. return View(result);
  27. }
  28. }
  29. }

Now, you need to pass an anonymous object to pass arguments as shown below:

  1. @await Component.InvokeAsync("CountersWidget", new
  2. {
  3. startDate = DateTime.Now.Subtract(TimeSpan.FromDays(7)),
  4. endDate = DateTime.Now
  5. })

Widget Name

Default name of the view components are calculated based on the name of the view component type. If your view component type is MySimpleWidgetViewComponent then the widget name will be MySimpleWidget (removes ViewComponent postfix). This is how ASP.NET Core calculates a view component’s name.

To customize widget’s name, just use the standard ViewComponent attribute of ASP.NET Core:

  1. using Microsoft.AspNetCore.Mvc;
  2. using Volo.Abp.AspNetCore.Mvc;
  3. using Volo.Abp.AspNetCore.Mvc.UI.Widgets;
  4. namespace DashboardDemo.Web.Pages.Components.MySimpleWidget
  5. {
  6. [Widget]
  7. [ViewComponent(Name = "MyCustomNamedWidget")]
  8. public class MySimpleWidgetViewComponent : AbpViewComponent
  9. {
  10. public IViewComponentResult Invoke()
  11. {
  12. return View("~/Pages/Components/MySimpleWidget/Default.cshtml");
  13. }
  14. }
  15. }

ABP will respect to the custom name by handling the widget.

If the view component name and the folder name of the view component don’t match, you may need to manually write the view path as done in this example.

Display Name

You can also define a human-readable, localizable display name for the widget. This display name then can be used on the UI when needed. Display name is optional and can be defined using properties of the Widget attribute:

  1. using DashboardDemo.Localization;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Volo.Abp.AspNetCore.Mvc;
  4. using Volo.Abp.AspNetCore.Mvc.UI.Widgets;
  5. namespace DashboardDemo.Web.Pages.Components.MySimpleWidget
  6. {
  7. [Widget(
  8. DisplayName = "MySimpleWidgetDisplayName", //Localization key
  9. DisplayNameResource = typeof(DashboardDemoResource) //localization resource
  10. )]
  11. public class MySimpleWidgetViewComponent : AbpViewComponent
  12. {
  13. public IViewComponentResult Invoke()
  14. {
  15. return View();
  16. }
  17. }
  18. }

See the localization document to learn about localization resources and keys.

Style & Script Dependencies

There are some challenges when your widget has script and style files;

  • Any page uses the widget should also include the its script & styles files into the page.
  • The page should also care about depended libraries/files of the widget.

ABP solves these issues when you properly relate the resources with the widget. You don’t care about dependencies of the widget while using it.

Defining as Simple File Paths

The example widget below adds a style and a script file:

  1. using Microsoft.AspNetCore.Mvc;
  2. using Volo.Abp.AspNetCore.Mvc;
  3. using Volo.Abp.AspNetCore.Mvc.UI.Widgets;
  4. namespace DashboardDemo.Web.Pages.Components.MySimpleWidget
  5. {
  6. [Widget(
  7. StyleFiles = new[] { "/Pages/Components/MySimpleWidget/Default.css" },
  8. ScriptFiles = new[] { "/Pages/Components/MySimpleWidget/Default.js" }
  9. )]
  10. public class MySimpleWidgetViewComponent : AbpViewComponent
  11. {
  12. public IViewComponentResult Invoke()
  13. {
  14. return View();
  15. }
  16. }
  17. }

ABP takes account these dependencies and properly adds to the view/page when you use the widget. Style/script files can be physical or virtual. It is completely integrated to the Virtual File System.

Defining Bundle Contributors

All resources for used widgets in a page are added as a bundle (bundled & minified in production if you don’t configure otherwise). In addition to adding a simple file, you can take full power of the bundle contributors.

The sample code below does the same with the code above, but defines and uses bundle contributors:

  1. using System.Collections.Generic;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Volo.Abp.AspNetCore.Mvc;
  4. using Volo.Abp.AspNetCore.Mvc.UI.Bundling;
  5. using Volo.Abp.AspNetCore.Mvc.UI.Widgets;
  6. namespace DashboardDemo.Web.Pages.Components.MySimpleWidget
  7. {
  8. [Widget(
  9. StyleTypes = new []{ typeof(MySimpleWidgetStyleBundleContributor) },
  10. ScriptTypes = new[]{ typeof(MySimpleWidgetScriptBundleContributor) }
  11. )]
  12. public class MySimpleWidgetViewComponent : AbpViewComponent
  13. {
  14. public IViewComponentResult Invoke()
  15. {
  16. return View();
  17. }
  18. }
  19. public class MySimpleWidgetStyleBundleContributor : BundleContributor
  20. {
  21. public override void ConfigureBundle(BundleConfigurationContext context)
  22. {
  23. context.Files
  24. .AddIfNotContains("/Pages/Components/MySimpleWidget/Default.css");
  25. }
  26. }
  27. public class MySimpleWidgetScriptBundleContributor : BundleContributor
  28. {
  29. public override void ConfigureBundle(BundleConfigurationContext context)
  30. {
  31. context.Files
  32. .AddIfNotContains("/Pages/Components/MySimpleWidget/Default.js");
  33. }
  34. }
  35. }

Bundle contribution system is very powerful. If your widget uses a JavaScript library to render a chart, then you can declare it as a dependency, so the JavaScript library is automatically added to the page if it wasn’t added before. In this way, the page using your widget doesn’t care about the dependencies.

See the bundling & minification documentation for more information about that system.

RefreshUrl

A widget may design a RefreshUrl that is used whenever the widget needs to be refreshed. If it is defined, the widget is re-rendered on the server side on every refresh (see the refresh method of the WidgetManager below).

  1. [Widget(RefreshUrl = "Widgets/Counters")]
  2. public class CountersWidgetViewComponent : AbpViewComponent
  3. {
  4. }

Once you define a RefreshUrl for your widget, you need to provide an endpoint to render and return it:

  1. [Route("Widgets")]
  2. public class CountersWidgetController : AbpController
  3. {
  4. [HttpGet]
  5. [Route("Counters")]
  6. public IActionResult Counters(DateTime startDate, DateTime endDate)
  7. {
  8. return ViewComponent("CountersWidget", new {startDate, endDate});
  9. }
  10. }

Widgets/Counters route matches to the RefreshUrl declared before.

A widget supposed to be refreshed in two ways: In the first way, when you use a RefreshUrl, it re-rendered on the server and replaced by the HTML returned from server. In the second way the widget gets data (generally a JSON object) from server and refreshes itself in the client side (see the refresh method in the Widget JavaScript API section).

JavaScript API

A widget may need to be rendered and refreshed in the client side. In such cases, you can use ABP’s WidgetManager and define APIs for your widgets.

WidgetManager

WidgetManager is used to initialize and refresh one or more widgets. Create a new WidgetManager as shown below:

  1. $(function() {
  2. var myWidgetManager = new abp.WidgetManager('#MyDashboardWidgetsArea');
  3. })

MyDashboardWidgetsArea may contain one or more widgets inside.

Using the WidgetManager inside document.ready (like above) is a good practice since its functions use the DOM and need DOM to be ready.

WidgetManager.init()

init simply initializes the WidgetManager and calls init methods of the related widgets if they define (see Widget JavaScript API section below)

  1. myWidgetManager.init();

WidgetManager.refresh()

refresh method refreshes all widgets related to this WidgetManager:

  1. myWidgetManager.refresh();

WidgetManager Options

WidgetManager has some additional options.

Filter Form

If your widgets require parameters/filters then you will generally have a form to filter the widgets. In such cases, you can create a form that has some form elements and a dashboard area with some widgets inside. Example:

  1. <form method="get" id="MyDashboardFilterForm">
  2. ...form elements
  3. </form>
  4. <div id="MyDashboardWidgetsArea" data-widget-filter="#MyDashboardFilterForm">
  5. ...widgets
  6. </div>

data-widget-filter attribute relates the form with the widgets. Whenever the form is submitted, all the widgets are automatically refreshed with the form fields as the filter.

Instead of the data-widget-filter attribute, you can use the filterForm parameter of the WidgetManager constructor. Example:

  1. var myWidgetManager = new abp.WidgetManager({
  2. wrapper: '#MyDashboardWidgetsArea',
  3. filterForm: '#MyDashboardFilterForm'
  4. });
Filter Callback

You may want to have a better control to provide filters while initializing and refreshing the widgets. In this case, you can use the filterCallback option:

  1. var myWidgetManager = new abp.WidgetManager({
  2. wrapper: '#MyDashboardWidgetsArea',
  3. filterCallback: function() {
  4. return $('#MyDashboardFilterForm').serializeFormToObject();
  5. }
  6. });

This example shows the default implementation of the filterCallback. You can return any JavaScript object with fields. Example:

  1. filterCallback: function() {
  2. return {
  3. 'startDate': $('#StartDateInput').val(),
  4. 'endDate': $('#EndDateInput').val()
  5. };
  6. }

The returning filters are passed to all widgets on init and refresh.

Widget JavaScript API

A widget can define a JavaScript API that is invoked by the WidgetManager when needed. The code sample below can be used to start to define an API for a widget.

  1. (function () {
  2. abp.widgets.NewUserStatisticWidget = function ($wrapper) {
  3. var getFilters = function () {
  4. return {
  5. ...
  6. };
  7. }
  8. var refresh = function (filters) {
  9. ...
  10. };
  11. var init = function (filters) {
  12. ...
  13. };
  14. return {
  15. getFilters: getFilters,
  16. init: init,
  17. refresh: refresh
  18. };
  19. };
  20. })();

NewUserStatisticWidget is the name of the widget here. It should match the widget name defined in the server side. All of the functions are optional.

getFilters

If the widget has internal custom filters, this function should return the filter object. Example:

  1. var getFilters = function() {
  2. return {
  3. frequency: $wrapper.find('.frequency-filter option:selected').val()
  4. };
  5. }

This method is used by the WidgetManager while building filters.

init

Used to initialize the widget when needed. It has a filter argument that can be used while getting data from server. init method is used when WidgetManager.init() function is called. It is also called if your widget requires a full re-load on refresh. See the RefreshUrl widget option.

refresh

Used to refresh the widget when needed. It has a filter argument that can be used while getting data from server. refresh method is used whenever WidgetManager.refresh() function is called.

Authorization

Some widgets may need to be available only for authenticated or authorized users. In this case, use the following properties of the Widget attribute:

  • RequiresAuthentication (bool): Set to true to make this widget usable only for authentication users (user have logged in to the application).
  • RequiredPolicies (List<string>): A list of policy names to authorize the user. See the authorization document for more info about policies.

Example:

  1. using Microsoft.AspNetCore.Mvc;
  2. using Volo.Abp.AspNetCore.Mvc;
  3. using Volo.Abp.AspNetCore.Mvc.UI.Widgets;
  4. namespace DashboardDemo.Web.Pages.Components.MySimpleWidget
  5. {
  6. [Widget(RequiredPolicies = new[] { "MyPolicyName" })]
  7. public class MySimpleWidgetViewComponent : AbpViewComponent
  8. {
  9. public IViewComponentResult Invoke()
  10. {
  11. return View();
  12. }
  13. }
  14. }

WidgetOptions

As alternative to the Widget attribute, you can use the AbpWidgetOptions to configure widgets:

  1. Configure<AbpWidgetOptions>(options =>
  2. {
  3. options.Widgets.Add<MySimpleWidgetViewComponent>();
  4. });

Write this into the ConfigureServices method of your module. All the configuration done with the Widget attribute is also possible with the AbpWidgetOptions. Example configuration that adds a style for the widget:

  1. Configure<AbpWidgetOptions>(options =>
  2. {
  3. options.Widgets
  4. .Add<MySimpleWidgetViewComponent>()
  5. .WithStyles("/Pages/Components/MySimpleWidget/Default.css");
  6. });

Tip: AbpWidgetOptions can also be used to get an existing widget and change its configuration. This is especially useful if you want to modify the configuration of a widget inside a module used by your application. Use options.Widgets.Find to get an existing WidgetDefinition.

See Also