There are multiple versions of this document. Pick the options that suit you best.

UI
Database

Web Application Development Tutorial - Part 9: Authors: User Interface

About This Tutorial

In this tutorial series, you will build an ABP based web application named Acme.BookStore. This application is used to manage a list of books and their authors. It is developed using the following technologies:

  • MongoDB as the database provider.
  • MAUI / Blazor Hybrid as the UI Framework.

This tutorial is organized as the following parts;

Download the Source Code

This tutorial has multiple versions based on your UI and Database preferences. We've prepared a few combinations of the source code to be downloaded:

If you encounter the "filename too long" or "unzip" error on Windows, please see this guide.

Introduction

This part explains how to create a CRUD page for the Author entity introduced in the previous parts.

The Author Management Page

Authors Razor Component

Create a new Razor Component Page, /Pages/Authors.razor, in the Acme.BookStore.MauiBlazor project with the following content:

@page "/authors"
@using Acme.BookStore.Authors
@using Volo.Abp.AspNetCore.Components.Web.Theming.Layout
@inherits BookStoreComponentBase
@inject IAuthorAppService AuthorAppService


<CascadingValue Value="this">
    @* ************************* PAGE HEADER ************************* *@
    <PageHeader Title="@L["Authors"]" Toolbar="@Toolbar">
    </PageHeader>
    <Card>
        <CardBody>
            <DataGrid TItem="AuthorDto"
                      Data="AuthorList"
                      ReadData="OnDataGridReadAsync"
                      CurrentPage="CurrentPage"
                      TotalItems="TotalCount"
                      ShowPager="true"
                      PageSize="PageSize">
                <DataGridColumns>
                    <DataGridColumn Width="150px"
                                    TItem="AuthorDto"
                                    Field="@nameof(AuthorDto.Id)"
                                    Sortable="false"
                                    Caption="@L["Actions"]">
                        <DisplayTemplate>
                            <Dropdown>
                                <DropdownToggle Color="Color.Primary">
                                    @L["Actions"]
                                </DropdownToggle>
                                <DropdownMenu>
                                    @if (CanEditAuthor)
                                    {
                                        <DropdownItem Clicked="() => OpenEditAuthorModal(context)">
                                            @L["Edit"]
                                        </DropdownItem>
                                    }
                                    @if (CanDeleteAuthor)
                                    {
                                        <DropdownItem Clicked="() => DeleteAuthorAsync(context)">
                                            @L["Delete"]
                                        </DropdownItem>
                                    }
                                </DropdownMenu>
                            </Dropdown>
                        </DisplayTemplate>
                    </DataGridColumn>
                    <DataGridColumn TItem="AuthorDto"
                                    Field="@nameof(AuthorDto.Name)"
                                    Caption="@L["Name"]"></DataGridColumn>
                    <DataGridColumn TItem="AuthorDto"
                                    Field="@nameof(AuthorDto.BirthDate)"
                                    Caption="@L["BirthDate"]">
                        <DisplayTemplate>
                            @context.BirthDate.ToShortDateString()
                        </DisplayTemplate>
                    </DataGridColumn>
                </DataGridColumns>
            </DataGrid>
        </CardBody>
    </Card>

    <Modal @ref="CreateAuthorModal">
        <ModalBackdrop />
        <ModalContent IsCentered="true">
            <ModalHeader>
                <ModalTitle>@L["NewAuthor"]</ModalTitle>
                <CloseButton Clicked="CloseCreateAuthorModal" />
            </ModalHeader>
            <ModalBody>
                <Field>
                    <FieldLabel>@L["Name"]</FieldLabel>
                    <TextEdit @bind-text="@NewAuthor.Name" />
                </Field>
                <Field>
                    <FieldLabel>@L["BirthDate"]</FieldLabel>
                    <DateEdit TValue="DateTime" @bind-Date="@NewAuthor.BirthDate" />
                </Field>
                <Field>
                    <FieldLabel>@L["ShortBio"]</FieldLabel>
                    <MemoEdit Rows="5" @bind-text="@NewAuthor.ShortBio" />
                </Field>
            </ModalBody>
            <ModalFooter>
                <Button Color="Color.Secondary"
                        Clicked="CloseCreateAuthorModal">
                    @L["Cancel"]
                </Button>
                <Button Color="Color.Primary"
                        Clicked="CreateAuthorAsync">
                    @L["Save"]
                </Button>
            </ModalFooter>
        </ModalContent>
    </Modal>

    <Modal @ref="EditAuthorModal">
        <ModalBackdrop />
        <ModalContent IsCentered="true">
            <ModalHeader>
                <ModalTitle>@EditingAuthor.Name</ModalTitle>
                <CloseButton Clicked="CloseEditAuthorModal" />
            </ModalHeader>
            <ModalBody>
                <Field>
                    <FieldLabel>@L["Name"]</FieldLabel>
                    <TextEdit @bind-text="@EditingAuthor.Name" />
                </Field>
                <Field>
                    <FieldLabel>@L["BirthDate"]</FieldLabel>
                    <DateEdit TValue="DateTime" @bind-Date="@EditingAuthor.BirthDate" />
                </Field>
                <Field>
                    <FieldLabel>@L["ShortBio"]</FieldLabel>
                    <MemoEdit Rows="5" @bind-text="@EditingAuthor.ShortBio" />
                </Field>
            </ModalBody>
            <ModalFooter>
                <Button Color="Color.Secondary"
                        Clicked="CloseEditAuthorModal">
                    @L["Cancel"]
                </Button>
                <Button Color="Color.Primary"
                        Clicked="UpdateAuthorAsync">
                    @L["Save"]
                </Button>
            </ModalFooter>
        </ModalContent>
    </Modal>
</CascadingValue>
  • This code is similar to the Books.razor, except it doesn't inherit from the BlazorisePageBase, but uses its own implementation.
  • Injects the IAuthorAppService to consume the server side HTTP APIs from the UI. We can directly inject application service interfaces and use just like regular method calls by the help of Dynamic C# HTTP API Client Proxy System, which performs REST API calls for us. See the Authors class below to see the usage.
  • Injects the IAuthorizationService to check permissions.
  • Injects the IObjectMapper for object to object mapping.

Create a new code behind file, Authors.razor.cs, under the Pages folder, with the following content:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Acme.BookStore.Authors;
using Acme.BookStore.Permissions;
using Blazorise;
using Blazorise.DataGrid;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.Application.Dtos;
using Volo.Abp.AspNetCore.Components.Web.Theming.PageToolbars;

namespace Acme.BookStore.MauiBlazor.Pages; 

public partial class Authors
{
    private IReadOnlyList<AuthorDto> AuthorList { get; set; }
    private int PageSize { get; } = LimitedResultRequestDto.DefaultMaxResultCount;
    private int CurrentPage { get; set; } = 1;
    private string CurrentSorting { get; set; }
    private int TotalCount { get; set; }
    private bool CanEditAuthor { get; set; }
    private bool CanDeleteAuthor { get; set; }
    private CreateAuthorDto NewAuthor { get; set; }
    private Guid EditingAuthorId { get; set; }
    private UpdateAuthorDto EditingAuthor { get; set; }
    private Modal CreateAuthorModal { get; set; }
    private Modal EditAuthorModal { get; set; }
    protected PageToolbar Toolbar { get; } = new();
    public Authors()
    {
        NewAuthor = new CreateAuthorDto();
        EditingAuthor = new UpdateAuthorDto();
    }
    protected ValueTask SetToolbarItemsAsync()
    {
        Toolbar.AddButton(L["NewAuthor"],
            OpenCreateAuthorModal,
            IconName.Add,
            requiredPolicyName: BookStorePermissions.Authors.Create);

        return ValueTask.CompletedTask;
    }
    protected override async Task OnInitializedAsync()
    {
        await SetPermissionsAsync();
        await GetAuthorsAsync();
        await SetToolbarItemsAsync();
    }
    private async Task SetPermissionsAsync()
    {
        CanEditAuthor = await AuthorizationService
            .IsGrantedAsync(BookStorePermissions.Authors.Edit);

        CanDeleteAuthor = await AuthorizationService
            .IsGrantedAsync(BookStorePermissions.Authors.Delete);
    }
    private async Task GetAuthorsAsync()
    {
        var result = await AuthorAppService.GetListAsync(
            new GetAuthorListDto
            {
                MaxResultCount = PageSize,
                SkipCount = (CurrentPage - 1) * PageSize,
                Sorting = CurrentSorting
            }
        );
        AuthorList = result.Items;
        TotalCount = (int)result.TotalCount;
    }
    private async Task OnDataGridReadAsync(DataGridReadDataEventArgs<AuthorDto> e)
    {
        CurrentSorting = e.Columns
            .Where(c => c.SortDirection != SortDirection.Default)
            .Select(c => c.Field + (c.SortDirection == SortDirection.Descending ? " DESC" : ""))
            .JoinAsString(",");
        CurrentPage = e.Page;
        await GetAuthorsAsync();
        StateHasChanged();
    }
    private Task OpenCreateAuthorModal()
    {
        NewAuthor = new CreateAuthorDto();
        CreateAuthorModal.Show();

        return Task.CompletedTask;
    }
    private void CloseCreateAuthorModal()
    {
        CreateAuthorModal.Hide();
    }
    private void OpenEditAuthorModal(AuthorDto author)
    {
        EditingAuthorId = author.Id;
        EditingAuthor = ObjectMapper.Map<AuthorDto, UpdateAuthorDto>(author);
        EditAuthorModal.Show();
    }
    private async Task DeleteAuthorAsync(AuthorDto author)
    {
        var confirmMessage = L["AuthorDeletionConfirmationMessage", author.Name];
        if (!await Message.Confirm(confirmMessage))
        {
            return;
        }
        await AuthorAppService.DeleteAsync(author.Id);
        await GetAuthorsAsync();
    }
    private void CloseEditAuthorModal()
    {
        EditAuthorModal.Hide();
    }
    private async Task CreateAuthorAsync()
    {
        await AuthorAppService.CreateAsync(NewAuthor);
        await GetAuthorsAsync();
        CreateAuthorModal.Hide();
    }
    private async Task UpdateAuthorAsync()
    {
        await AuthorAppService.UpdateAsync(EditingAuthorId, EditingAuthor);
        await GetAuthorsAsync();
        EditAuthorModal.Hide();
    }
}

This class typically defines the properties and methods used by the Authors.razor page.

Object Mapping

Authors class uses the IObjectMapper in the OpenEditAuthorModal method. So, we need to define this mapping.

Open the BookStoreBlazorAutoMapperProfile.cs in the Acme.BookStore.MauiBlazor project and add the following mapping code in the constructor:

CreateMap<AuthorDto, UpdateAuthorDto>();

You will need to declare a using Acme.BookStore.Authors; statement to the beginning of the file.

Add to the Main Menu

Open the BookStoreMenuContributor.cs in the Acme.BookStore.MauiBlazor project and add the following code to the end of the ConfigureMainMenuAsync method:

if (await context.IsGrantedAsync(BookStorePermissions.Authors.Default))
{
    bookStoreMenu.AddItem(new ApplicationMenuItem(
        "BooksStore.Authors",
        l["Menu:Authors"],
        url: "/authors"
    ));
}

Localizations

We should complete the localizations we've used above. Open the en.json file under the Localization/BookStore folder of the Acme.BookStore.Domain.Shared project and add the following entries:

"Menu:Authors": "Authors",
"Authors": "Authors",
"AuthorDeletionConfirmationMessage": "Are you sure to delete the author '{0}'?",
"BirthDate": "Birth date",
"NewAuthor": "New author"

Run the Application

Run and login to the application. If you don't see the Authors menu item under the Book Store menu, that means you don't have the permission yet. Go to the identity/roles page, click to the Actions button and select the Permissions action for the admin role:

bookstore-author-permissions

As you see, the admin role has no Author Management permissions yet. Click to the checkboxes and save the modal to grant the necessary permissions. You will see the Authors menu item under the Book Store in the main menu, after refreshing the page:

bookstore-authors-page

That's all! This is a fully working CRUD page, you can create, edit and delete the authors.

Tip: If you run the .DbMigrator console application after defining a new permission, it automatically grants these new permissions to the admin role and you don't need to manually grant the permissions yourself.

The Next Part

See the next part of this tutorial.

Was this page helpful?

Please make a selection.

To help us improve, please share your reason for the negative feedback in the field below.

Please enter a note.

Thank you for your valuable feedback!

Please note that although we cannot respond to feedback, our team will use your comments to improve the experience.

In this document
Community Talks

Building Modular Monolith Applications Using .Net and ABP Framework

17 Oct, 20:00
Online
Register Now
Mastering ABP Framework Book
Mastering ABP Framework

This book will help you gain a complete understanding of the framework and modern web application development techniques.

Learn More