Web Application Development Tutorial - Part 2: The Book List Page

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 tutorial has multiple versions based on your UI and Database preferences. We’ve prepared two combinations of the source code to be downloaded:

Video Tutorial

This part is also recorded as a video tutorial and published on YouTube.

Dynamic JavaScript Proxies

It’s common to call the HTTP API endpoints via AJAX from the JavaScript side. You can use $.ajax or another tool to call the endpoints. However, ABP offers a better way.

ABP dynamically creates JavaScript Proxies for all API endpoints. So, you can use any endpoint just like calling a JavaScript function.

Testing in the Developer Console

You can easily test the JavaScript proxies using your favorite browser’s Developer Console. Run the application, open your browser’s developer tools (shortcut is generally F12), switch to the Console tab, type the following code and press enter:

  1. acme.bookStore.books.book.getList({}).done(function (result) { console.log(result); });
  • acme.bookStore.books is the namespace of the BookAppService converted to camelCase.
  • book is the conventional name for the BookAppService (removed AppService postfix and converted to camelCase).
  • getList is the conventional name for the GetListAsync method defined in the CrudAppService base class (removed Async postfix and converted to camelCase).
  • {} argument is used to send an empty object to the GetListAsync method which normally expects an object of type PagedAndSortedResultRequestDto that is used to send paging and sorting options to the server (all properties are optional with default values, so you can send an empty object).
  • getList function returns a promise. You can pass a callback to the then (or done) function to get the result returned from the server.

Running this code produces the following output:

bookstore-javascript-proxy-console

You can see the book list returned from the server. You can also check the network tab of the developer tools to see the client to server communication:

bookstore-getlist-result-network

Let’s create a new book using the create function:

  1. acme.bookStore.books.book.create({
  2. name: 'Foundation',
  3. type: 7,
  4. publishDate: '1951-05-24',
  5. price: 21.5
  6. }).then(function (result) {
  7. console.log('successfully created the book with id: ' + result.id);
  8. });

You should see a message in the console something like that:

  1. successfully created the book with id: 439b0ea8-923e-8e1e-5d97-39f2c7ac4246

Check the Books table in the database to see the new book row. You can try get, update and delete functions yourself.

We will use these dynamic proxy functions in the next sections to communicate to the server.

Localization

Before starting to the UI development, we first want to prepare the localization texts (you normally do when needed while developing your application).

Localization texts are located under the Localization/BookStore folder of the Acme.BookStore.Domain.Shared project:

bookstore-localization-files

Open the en.json (the English translations) file and change the content as below:

  1. {
  2. "Culture": "en",
  3. "Texts": {
  4. "Menu:Home": "Home",
  5. "Welcome": "Welcome",
  6. "LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information, visit abp.io.",
  7. "Menu:BookStore": "Book Store",
  8. "Menu:Books": "Books",
  9. "Actions": "Actions",
  10. "Close": "Close",
  11. "Delete": "Delete",
  12. "Edit": "Edit",
  13. "PublishDate": "Publish date",
  14. "NewBook": "New book",
  15. "Name": "Name",
  16. "Type": "Type",
  17. "Price": "Price",
  18. "CreationTime": "Creation time",
  19. "AreYouSure": "Are you sure?",
  20. "AreYouSureToDelete": "Are you sure you want to delete this item?",
  21. "Enum:BookType:0": "Undefined",
  22. "Enum:BookType:1": "Adventure",
  23. "Enum:BookType:2": "Biography",
  24. "Enum:BookType:3": "Dystopia",
  25. "Enum:BookType:4": "Fantastic",
  26. "Enum:BookType:5": "Horror",
  27. "Enum:BookType:6": "Science",
  28. "Enum:BookType:7": "Science fiction",
  29. "Enum:BookType:8": "Poetry"
  30. }
  31. }
  • Localization key names are arbitrary. You can set any name. We prefer some conventions for specific text types;
    • Add Menu: prefix for menu items.
    • Use Enum:<enum-type>:<enum-value> naming convention to localize the enum members. When you do it like that, ABP can automatically localize the enums in some proper cases.

If a text is not defined in the localization file, it fallbacks to the localization key (as ASP.NET Core’s standard behavior).

ABP’s localization system is built on ASP.NET Core’s standard localization system and extends it in many ways. See the localization document for details.

Create a Books Page

It’s time to create something visible and usable! Instead of classic MVC, we will use the Razor Pages UI approach which is recommended by Microsoft.

Create Books folder under the Pages folder of the Acme.BookStore.Web project. Add a new Razor Page by right clicking the Books folder then selecting Add > Razor Page menu item. Name it as Index:

bookstore-add-index-page

Open the Index.cshtml and change the whole content as shown below:

  1. @page
  2. @using Acme.BookStore.Web.Pages.Books
  3. @model IndexModel
  4. <h2>Books</h2>

Index.cshtml.cs content should be like that:

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

Add Books Page to the Main Menu

Open the BookStoreMenuContributor class in the Menus folder and add the following code to the end of the ConfigureMainMenuAsync method:

  1. context.Menu.AddItem(
  2. new ApplicationMenuItem(
  3. "BooksStore",
  4. l["Menu:BookStore"],
  5. icon: "fa fa-book"
  6. ).AddItem(
  7. new ApplicationMenuItem(
  8. "BooksStore.Books",
  9. l["Menu:Books"],
  10. url: "/Books"
  11. )
  12. )
  13. );

Run the project, login to the application with the username admin and the password 1q2w3E* and see the new menu item has been added to the main menu:

bookstore-menu-items

When you click to the Books menu item under the Book Store parent, you are being redirected to the new empty Books Page.

Book List

We will use the Datatables.net jQuery library to show the book list. Datatables library completely work via AJAX, it is fast, popular and provides a good user experience.

Datatables library is configured in the startup template, so you can directly use it in any page without including any style or script file to your page.

Index.cshtml

Change the Pages/Books/Index.cshtml as following:

  1. @page
  2. @using Acme.BookStore.Localization
  3. @using Acme.BookStore.Web.Pages.Books
  4. @using Microsoft.Extensions.Localization
  5. @model IndexModel
  6. @inject IStringLocalizer<BookStoreResource> L
  7. @section scripts
  8. {
  9. <abp-script src="/Pages/Books/Index.js" />
  10. }
  11. <abp-card>
  12. <abp-card-header>
  13. <h2>@L["Books"]</h2>
  14. </abp-card-header>
  15. <abp-card-body>
  16. <abp-table striped-rows="true" id="BooksTable"></abp-table>
  17. </abp-card-body>
  18. </abp-card>
  • abp-script tag helper is used to add external scripts to the page. It has many additional features compared to standard script tag. It handles minification and versioning. See the bundling & minification document for details.
  • abp-card is a tag helper for Twitter Bootstrap’s card component. There are other useful tag helpers provided by the ABP Framework to easily use most of the bootstrap components. You could use the regular HTML tags instead of these tag helpers, but using tag helpers reduces HTML code and prevents errors by help the of IntelliSense and compile time type checking. Further information, see the tag helpers document.

Index.js

Create an Index.js file under the Pages/Books folder:

bookstore-index-js-file

The content of the file is shown below:

  1. $(function () {
  2. var l = abp.localization.getResource('BookStore');
  3. var dataTable = $('#BooksTable').DataTable(
  4. abp.libs.datatables.normalizeConfiguration({
  5. serverSide: true,
  6. paging: true,
  7. order: [[1, "asc"]],
  8. searching: false,
  9. scrollX: true,
  10. ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList),
  11. columnDefs: [
  12. {
  13. title: l('Name'),
  14. data: "name"
  15. },
  16. {
  17. title: l('Type'),
  18. data: "type",
  19. render: function (data) {
  20. return l('Enum:BookType:' + data);
  21. }
  22. },
  23. {
  24. title: l('PublishDate'),
  25. data: "publishDate",
  26. render: function (data) {
  27. return luxon
  28. .DateTime
  29. .fromISO(data, {
  30. locale: abp.localization.currentCulture.name
  31. }).toLocaleString();
  32. }
  33. },
  34. {
  35. title: l('Price'),
  36. data: "price"
  37. },
  38. {
  39. title: l('CreationTime'), data: "creationTime",
  40. render: function (data) {
  41. return luxon
  42. .DateTime
  43. .fromISO(data, {
  44. locale: abp.localization.currentCulture.name
  45. }).toLocaleString(luxon.DateTime.DATETIME_SHORT);
  46. }
  47. }
  48. ]
  49. })
  50. );
  51. });
  • abp.localization.getResource gets a function that is used to localize text using the same JSON file defined in the server side. In this way, you can share the localization values with the client side.
  • abp.libs.datatables.normalizeConfiguration is a helper function defined by the ABP Framework. There’s no requirement to use it, but it simplifies the Datatables configuration by providing conventional default values for missing options.
  • abp.libs.datatables.createAjax is another helper function to adapt ABP’s dynamic JavaScript API proxies to Datatable‘s expected parameter format
  • acme.bookStore.books.book.getList is the dynamic JavaScript proxy function introduced before.
  • luxon library is also a standard library that is pre-configured in the solution, so you can use to perform date/time operations easily.

See Datatables documentation for all configuration options.

Run the Final Application

You can run the application! The final UI of this part is shown below:

Book list

This is a fully working, server side paged, sorted and localized table of books.

The Next Part

See the next part of this tutorial.