The Use of Navigation Menu in ABP Frame and the Method of Obtaining Menu in JavaScript API

  • 2021-08-03 09:54:07
  • OfStack

Every WEB application has a navigation menu, and Abp also provides users with a common way to create and display menus.

Create Menu
1 An application may contain different modules, and each module may have its own menu item. In Abp, you need to create a class derived from NavigationProvider to define a menu item.
Suppose we have a main menu like this:

Tasks Reports Administration 1 User Management 2 Role Management

As can be seen from the above, the Administration menu item has two submenu items. The corresponding generation method is as follows:


 public class SimpleTaskSystemNavigationProvider : NavigationProvider
{
  public override void SetNavigation(INavigationProviderContext context)
  {
    context.Manager.MainMenu
      .AddItem(
        new MenuItemDefinition(
          "Tasks",
          new LocalizableString("Tasks", "SimpleTaskSystem"),
          url: "/Tasks",
          icon: "fa fa-tasks"
          )
      ).AddItem(
        new MenuItemDefinition(
          "Reports",
          new LocalizableString("Reports", "SimpleTaskSystem"),
          url: "/Reports",
          icon: "fa fa-bar-chart"
          )
      ).AddItem(
        new MenuItemDefinition(
          "Administration",
          new LocalizableString("Administration", "SimpleTaskSystem"),
          icon: "fa fa-cogs"
          ).AddItem(
            new MenuItemDefinition(
              "UserManagement",
              new LocalizableString("UserManagement", "SimpleTaskSystem"),
              url: "/Administration/Users",
              icon: "fa fa-users",
              requiredPermissionName: "SimpleTaskSystem.Permissions.UserManagement"
              )
          ).AddItem(
            new MenuItemDefinition(
              "RoleManagement",
              new LocalizableString("RoleManagement", "SimpleTaskSystem"),
              url: "/Administration/Roles",
              icon: "fa fa-star",
              requiredPermissionName: "SimpleTaskSystem.Permissions.RoleManagement"
              )
          )
      );
  }
}


MenuItemDefinition can have a 1-only name, a name for localized display, an url and an icon. In addition, menu items may need to be combined with specific user rights (the relevant rights system is under development and has not been documented yet).
The InavigationProviderContext method can get an existing menu item and add a menu or menu item. Therefore, different modules can add their own menus.
After creating the navigation, you also need to register in the Abp configuration file when the corresponding module is pre-initialized:
Configuration.Navigation.Providers.Add < SimpleTaskSystemNavigationProvider > ();

Show menu
IuserNavigationManager can inject, retrieve, and display menus. You can create menus on the server side.
Abp Automatically generated javascript API enables users to retrieve menus on the client side with corresponding methods and objects in the namespace abp. nav. For example, using abp. nav. menus. MainMenu on the client can be used to get the main menu.
Let's look at the related aspects of JavaScript.

Ajax
Modern applications often use AJAX, especially single-page applications, which are almost the only means to communicate with servers. Implementing AJAX usually involves the following steps:
On the client side, you need to provide an URL and select a method to communicate with the server (GET, POST, PUT, DELETE). Execute the callback function after the request is completed, and the request result can be success or failure. If it fails, you need to give a prompt. If it succeeds, you need to execute the operation according to the return value. Usually, at the beginning of the request, you need to give information such as being processed or related busy waiting (such as page occlusion), and resume after the request is completed.
After receiving the request, the server verifies the request parameters and executes the server code. If there is an error or the verification fails, the specific reason should be given, and the data desired by the client should be returned when it is successful.
The ABP server supports standard ajax request/output. It is recommended that you use the ajax request method provided in abp. jquery. js. This method is based on ajax method of jquery, which can automatically handle the exception information of the server. Of course, if you are skilled at js, you can also write ajax according to your own needs.
ASP. NET Boilerplate request instance:


// Build Parameter Objects to Transfer 
var newPerson = {
  name: 'Dougles Adams',
  age: 42
};
// Call abp Adj. ajax Method 
abp.ajax({
  url: '/People/SavePerson',
  data: JSON.stringify(newPerson) // Convert to json String 
}).done(function(data) {
abp.notify.success('created new person with id = ' + data.personId);
});


You can also use the ajax method call of jquery, but you need to set the default request parameter under 1, dataType is set to 'json', type is set to 'POST' and contentType is set to 'application/json, you need to convert js object into json string when sending the request, and $. ajax1. You can also pass parameters to override abp. ajax's default parameter abp. ajax returns an promise type. You can write the following method by chain programming:


.done() // Success ,
.fail() // Failure, 
.then() // Callback nesting. 

The following simple example shows the SavePerson method that ajax requests PeopleController, and the record id returned after the server successfully creates the record can be obtained in. done ().


public class PeopleController : AbpController
{
  [HttpPost]
  public JsonResult SavePerson(SavePersonModel person)
  {
    //TODO: save new person to database and return new person's id
//TODO:  Create 1 A new one person Record and return the id
    return Json(new {PersonId = 42});
  }
}


SavePersonModel contains attributes such as name, age, etc. SavePerson is marked with HttpPost attribute abp. ajax is requested as POST by default. The return value is reduced to an anonymous object.

SavePersonModel contains attributes such as name, age, etc. SavePerson is marked with HttpPost attribute abp. ajax is requested as POST by default. The return value is reduced to an anonymous object.

AJAX Return Value (AJAX return messages)

We returned an anonymous object directly, and ABP wraps the return value with MvcAjaxResponse type. The actual return value type is as follows:


{
 "success": true, // Handle flags correctly 
 "result": {
  "personId": 42 // Data returned 
 },
 "error": null, // If an error occurs, result For null , here the object of the error message, containing the message And details Two attributes 
 "targetUrl": null, // Available 1 A url For client redirection, such as automatic build under 1 Page url
 "unAuthorizedRequest": false // Whether the authorization has been passed, and if the true The client should log in again 
}


If you inherit AbpController, the object returned by the Json method is always wrapped in this way. If no error occurs, in done (function (result, data) {}) of abp. ajax, the first parameter result is {"personId": 42} object, data is the original object, and inheriting AbpApiController in WebApi is the same mechanism.

Error Handling (Handling errors)

The return value is as follows:


{
 "targetUrl": null,
 "result": null,
 "success": false, // Represents an exception 
 "error": {
  "message": "An internal error occured during your request!", // Exceptions that are not caught, usually system exceptions, will be automatically logged. Specific prompt information can be configured in the configuration file, and can be searched 1 If it is thrown by the business, UserFriendlyException Anomaly, message For specific error messages 
  "details": "..." // Called by default when an exception occurs abp.message.error Function, you can use the abp.jquery.js Revise, unify 1 Handle error messages. 
 },
 "unAuthorizedRequest": false
}


Dynamic WebAPI (Dynamic Web API Layer)

Here, the WebAPI call function is dynamically generated according to Services:


// Usually we use ajax Will be written as follows, do 1 A simple encapsulation to reuse ajax Where the framework can help you generate simple invocation methods 
var savePerson = function(person) {
  return abp.ajax({
    url: '/People/SavePerson',
    data: JSON.stringify(person)
  });
};
// You need to build parameters when calling 
var newPerson = {
  name: 'Dougles Adams',
  age: 42
};
// Direct call method, how to generate the above call method can refer to the source code Abp.Web.Api In the project / WebApi/ Controllers/ Scripting/ jQuery Implementation under 
savePerson(newPerson).done(function(data) {
  abp.notify.success('created new person with id = ' + data.personId);
});



Related articles: