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:

  • Entity Framework Core as the ORM provider.
  • MVC / Razor Pages as the UI Framework.

This tutorial is organized as the following parts;

Download the Source Code

This tutorials has multiple versions based on your UI and Database preferences. We’ve prepared two combinations of the source code to be downloaded:

Introduction

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

The Book List Page

Create a new razor page, Index.cshtml under the Pages/Authors folder of the Acme.BookStore.Web project and change the content as given below.

Index.cshtml

  1. @page
  2. @using Acme.BookStore.Localization
  3. @using Acme.BookStore.Permissions
  4. @using Acme.BookStore.Web.Pages.Authors
  5. @using Microsoft.AspNetCore.Authorization
  6. @using Microsoft.Extensions.Localization
  7. @inject IStringLocalizer<BookStoreResource> L
  8. @inject IAuthorizationService AuthorizationService
  9. @model IndexModel
  10. @section scripts
  11. {
  12. <abp-script src="/Pages/Authors/Index.js"/>
  13. }
  14. <abp-card>
  15. <abp-card-header>
  16. <abp-row>
  17. <abp-column size-md="_6">
  18. <abp-card-title>@L["Authors"]</abp-card-title>
  19. </abp-column>
  20. <abp-column size-md="_6" class="text-right">
  21. @if (await AuthorizationService
  22. .IsGrantedAsync(BookStorePermissions.Authors.Create))
  23. {
  24. <abp-button id="NewAuthorButton"
  25. text="@L["NewAuthor"].Value"
  26. icon="plus"
  27. button-type="Primary"/>
  28. }
  29. </abp-column>
  30. </abp-row>
  31. </abp-card-header>
  32. <abp-card-body>
  33. <abp-table striped-rows="true" id="AuthorsTable"></abp-table>
  34. </abp-card-body>
  35. </abp-card>

This is a simple page similar to the Books page we had created before. It imports a JavaScript file which will be introduced below.

IndexModel.cshtml.cs

  1. using Microsoft.AspNetCore.Mvc.RazorPages;
  2. namespace Acme.BookStore.Web.Pages.Authors
  3. {
  4. public class IndexModel : PageModel
  5. {
  6. public void OnGet()
  7. {
  8. }
  9. }
  10. }

Index.js

  1. $(function () {
  2. var l = abp.localization.getResource('BookStore');
  3. var createModal = new abp.ModalManager(abp.appPath + 'Authors/CreateModal');
  4. var editModal = new abp.ModalManager(abp.appPath + 'Authors/EditModal');
  5. var dataTable = $('#AuthorsTable').DataTable(
  6. abp.libs.datatables.normalizeConfiguration({
  7. serverSide: true,
  8. paging: true,
  9. order: [[1, "asc"]],
  10. searching: false,
  11. scrollX: true,
  12. ajax: abp.libs.datatables.createAjax(acme.bookStore.authors.author.getList),
  13. columnDefs: [
  14. {
  15. title: l('Actions'),
  16. rowAction: {
  17. items:
  18. [
  19. {
  20. text: l('Edit'),
  21. visible:
  22. abp.auth.isGranted('BookStore.Authors.Edit'),
  23. action: function (data) {
  24. editModal.open({ id: data.record.id });
  25. }
  26. },
  27. {
  28. text: l('Delete'),
  29. visible:
  30. abp.auth.isGranted('BookStore.Authors.Delete'),
  31. confirmMessage: function (data) {
  32. return l(
  33. 'AuthorDeletionConfirmationMessage',
  34. data.record.name
  35. );
  36. },
  37. action: function (data) {
  38. acme.bookStore.authors.author
  39. .delete(data.record.id)
  40. .then(function() {
  41. abp.notify.info(
  42. l('SuccessfullyDeleted')
  43. );
  44. dataTable.ajax.reload();
  45. });
  46. }
  47. }
  48. ]
  49. }
  50. },
  51. {
  52. title: l('Name'),
  53. data: "name"
  54. },
  55. {
  56. title: l('BirthDate'),
  57. data: "birthDate",
  58. render: function (data) {
  59. return luxon
  60. .DateTime
  61. .fromISO(data, {
  62. locale: abp.localization.currentCulture.name
  63. }).toLocaleString();
  64. }
  65. }
  66. ]
  67. })
  68. );
  69. createModal.onResult(function () {
  70. dataTable.ajax.reload();
  71. });
  72. editModal.onResult(function () {
  73. dataTable.ajax.reload();
  74. });
  75. $('#NewAuthorButton').click(function (e) {
  76. e.preventDefault();
  77. createModal.open();
  78. });
  79. });

Briefly, this JavaScript page;

  • Creates a Data table with Actions, Name and BirthDate columns.
    • Actions column is used to add Edit and Delete actions.
    • BirthDate provides a render function to format the DateTime value using the luxon library.
  • Uses the abp.ModalManager to open Create and Edit modal forms.

This code is very similar to the Books page created before, so we will not explain it more.

Localizations

This page uses some localization keys we need to declare. Open the en.json file under the Localization/BookStore folder of the Acme.BookStore.Domain.Shared project and add the following entries:

  1. "Menu:Authors": "Authors",
  2. "Authors": "Authors",
  3. "AuthorDeletionConfirmationMessage": "Are you sure to delete the author '{0}'?",
  4. "BirthDate": "Birth date",
  5. "NewAuthor": "New author"

Notice that we’ve added more keys. They will be used in the next sections.

Add to the Main Menu

Open the BookStoreMenuContributor.cs in the Menus folder of the Acme.BookStore.Web project and add the following code in the end of the ConfigureMainMenuAsync method:

  1. if (await context.IsGrantedAsync(BookStorePermissions.Authors.Default))
  2. {
  3. bookStoreMenu.AddItem(new ApplicationMenuItem(
  4. "BooksStore.Authors",
  5. l["Menu:Authors"],
  6. url: "/Authors"
  7. ));
  8. }

Run the Application

Run and login to the application. You can not see the menu item since you don’t have 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

The page is fully working except New author and Actions/Edit since we haven’t implemented them yet.

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.

Create Modal

Create a new razor page, CreateModal.cshtml under the Pages/Authors folder of the Acme.BookStore.Web project and change the content as given below.

CreateModal.cshtml

  1. @page
  2. @using Acme.BookStore.Localization
  3. @using Acme.BookStore.Web.Pages.Authors
  4. @using Microsoft.Extensions.Localization
  5. @using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal
  6. @model CreateModalModel
  7. @inject IStringLocalizer<BookStoreResource> L
  8. @{
  9. Layout = null;
  10. }
  11. <form asp-page="/Authors/CreateModal">
  12. <abp-modal>
  13. <abp-modal-header title="@L["NewAuthor"].Value"></abp-modal-header>
  14. <abp-modal-body>
  15. <abp-input asp-for="Author.Name" />
  16. <abp-input asp-for="Author.BirthDate" />
  17. <abp-input asp-for="Author.ShortBio" />
  18. </abp-modal-body>
  19. <abp-modal-footer buttons="@(AbpModalButtons.Cancel|AbpModalButtons.Save)"></abp-modal-footer>
  20. </abp-modal>
  21. </form>

We had used dynamic forms of the ABP Framework for the books page before. We could use the same approach here, but we wanted to show how to do it manually. Actually, not so manually, because we’ve used abp-input tag helper in this case to simplify creating the form elements.

You can definitely use the standard Bootstrap HTML structure, but it requires to write a lot of code. abp-input automatically adds validation, localization and other standard elements based on the data type.

CreateModal.cshtml.cs

  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Threading.Tasks;
  4. using Acme.BookStore.Authors;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Form;
  7. namespace Acme.BookStore.Web.Pages.Authors
  8. {
  9. public class CreateModalModel : BookStorePageModel
  10. {
  11. [BindProperty]
  12. public CreateAuthorViewModel Author { get; set; }
  13. private readonly IAuthorAppService _authorAppService;
  14. public CreateModalModel(IAuthorAppService authorAppService)
  15. {
  16. _authorAppService = authorAppService;
  17. }
  18. public void OnGet()
  19. {
  20. Author = new CreateAuthorViewModel();
  21. }
  22. public async Task<IActionResult> OnPostAsync()
  23. {
  24. var dto = ObjectMapper.Map<CreateAuthorViewModel, CreateAuthorDto>(Author);
  25. await _authorAppService.CreateAsync(dto);
  26. return NoContent();
  27. }
  28. public class CreateAuthorViewModel
  29. {
  30. [Required]
  31. [StringLength(AuthorConsts.MaxNameLength)]
  32. public string Name { get; set; }
  33. [Required]
  34. [DataType(DataType.Date)]
  35. public DateTime BirthDate { get; set; }
  36. [TextArea]
  37. public string ShortBio { get; set; }
  38. }
  39. }
  40. }

This page model class simply injects and uses the IAuthorAppService to create a new author. The main difference between the book creation model class is that this one is declaring a new class, CreateAuthorViewModel, for the view model instead of re-using the CreateAuthorDto.

The main reason of this decision was to show you how to use a different model class inside the page. But there is one more benefit: We added two attributes to the class members, which were not present in the CreateAuthorDto:

  • Added [DataType(DataType.Date)] attribute to the BirthDate which shows a date picker on the UI for this property.
  • Added [TextArea] attribute to the ShortBio which shows a multi-line text area instead of a standard textbox.

In this way, you can specialize the view model class based on your UI requirements without touching to the DTO. As a result of this decision, we have used ObjectMapper to map CreateAuthorViewModel to CreateAuthorDto. To be able to do that, you need to add a new mapping code to the BookStoreWebAutoMapperProfile constructor:

  1. using Acme.BookStore.Authors; // ADDED NAMESPACE IMPORT
  2. using Acme.BookStore.Books;
  3. using AutoMapper;
  4. namespace Acme.BookStore.Web
  5. {
  6. public class BookStoreWebAutoMapperProfile : Profile
  7. {
  8. public BookStoreWebAutoMapperProfile()
  9. {
  10. CreateMap<BookDto, CreateUpdateBookDto>();
  11. // ADD a NEW MAPPING
  12. CreateMap<Pages.Authors.CreateModalModel.CreateAuthorViewModel,
  13. CreateAuthorDto>();
  14. }
  15. }
  16. }

“New author” button will work as expected and open a new model when you run the application again:

bookstore-new-author-modal

Edit Modal

Create a new razor page, EditModal.cshtml under the Pages/Authors folder of the Acme.BookStore.Web project and change the content as given below.

EditModal.cshtml

  1. @page
  2. @using Acme.BookStore.Localization
  3. @using Acme.BookStore.Web.Pages.Authors
  4. @using Microsoft.Extensions.Localization
  5. @using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal
  6. @model EditModalModel
  7. @inject IStringLocalizer<BookStoreResource> L
  8. @{
  9. Layout = null;
  10. }
  11. <form asp-page="/Authors/EditModal">
  12. <abp-modal>
  13. <abp-modal-header title="@L["Update"].Value"></abp-modal-header>
  14. <abp-modal-body>
  15. <abp-input asp-for="Author.Id" />
  16. <abp-input asp-for="Author.Name" />
  17. <abp-input asp-for="Author.BirthDate" />
  18. <abp-input asp-for="Author.ShortBio" />
  19. </abp-modal-body>
  20. <abp-modal-footer buttons="@(AbpModalButtons.Cancel|AbpModalButtons.Save)"></abp-modal-footer>
  21. </abp-modal>
  22. </form>

EditModal.cshtml.cs

  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Threading.Tasks;
  4. using Acme.BookStore.Authors;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Form;
  7. namespace Acme.BookStore.Web.Pages.Authors
  8. {
  9. public class EditModalModel : BookStorePageModel
  10. {
  11. [BindProperty]
  12. public EditAuthorViewModel Author { get; set; }
  13. private readonly IAuthorAppService _authorAppService;
  14. public EditModalModel(IAuthorAppService authorAppService)
  15. {
  16. _authorAppService = authorAppService;
  17. }
  18. public async Task OnGetAsync(Guid id)
  19. {
  20. var authorDto = await _authorAppService.GetAsync(id);
  21. Author = ObjectMapper.Map<AuthorDto, EditAuthorViewModel>(authorDto);
  22. }
  23. public async Task<IActionResult> OnPostAsync()
  24. {
  25. await _authorAppService.UpdateAsync(
  26. Author.Id,
  27. ObjectMapper.Map<EditAuthorViewModel, UpdateAuthorDto>(Author)
  28. );
  29. return NoContent();
  30. }
  31. public class EditAuthorViewModel
  32. {
  33. [HiddenInput]
  34. public Guid Id { get; set; }
  35. [Required]
  36. [StringLength(AuthorConsts.MaxNameLength)]
  37. public string Name { get; set; }
  38. [Required]
  39. [DataType(DataType.Date)]
  40. public DateTime BirthDate { get; set; }
  41. [TextArea]
  42. public string ShortBio { get; set; }
  43. }
  44. }
  45. }

This class is similar to the CreateModal.cshtml.cs while there are some main differences;

  • Uses the IAuthorAppService.GetAsync(...) method to get the editing author from the application layer.
  • EditAuthorViewModel has an additional Id property which is marked with the [HiddenInput] attribute that creates a hidden input for this property.

This class requires to add two object mapping declarations to the BookStoreWebAutoMapperProfile class:

  1. using Acme.BookStore.Authors;
  2. using Acme.BookStore.Books;
  3. using AutoMapper;
  4. namespace Acme.BookStore.Web
  5. {
  6. public class BookStoreWebAutoMapperProfile : Profile
  7. {
  8. public BookStoreWebAutoMapperProfile()
  9. {
  10. CreateMap<BookDto, CreateUpdateBookDto>();
  11. CreateMap<Pages.Authors.CreateModalModel.CreateAuthorViewModel,
  12. CreateAuthorDto>();
  13. // ADD THESE NEW MAPPINGS
  14. CreateMap<AuthorDto, Pages.Authors.EditModalModel.EditAuthorViewModel>();
  15. CreateMap<Pages.Authors.EditModalModel.EditAuthorViewModel,
  16. UpdateAuthorDto>();
  17. }
  18. }
  19. }

That’s all! You can run the application and try to edit an author.

The Next Part

See the next part of this tutorial.