The use of navigation menus in the ABP framework and the JavaScript API Access Menu Method _ Practical Tips

Source: Internet
Author: User
Tags anonymous error handling


Each Web application has a navigation menu, and ABP provides users with a common way to create and display menus.



Create a Menu
an application may contain different modules, and each module may have its own menu item. In ABP, you need to create a class that derives from Navigationprovider to define a menu item.
Let's say we have one of these main menus:


    • Tasks
    • Reports
    • Administration 1 User Management 2 role Management


From the above, the Administration menu item has two submenu items. The corresponding build 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 unique name, a name for localized display, a URL, and an icon, in addition, menu items may need to be combined with specific user rights (the relevant permission system is being developed and no documentation is currently being documented).
The Inavigationprovidercontext method can get an existing menu item, add a menu, or a menu item. As a result, different modules can add their own menus.
Once you have created the navigation, you also need to register to the ABP configuration file when the corresponding module is 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 APIs enable users to get menus on the client, corresponding methods and objects in the namespace Abp.nav. For example, you can use Abp.nav.menus.MainMenu on the client to get the main menu.
Let's look at the relevant aspects of JavaScript below.



Ajax
modern applications often use AJAX, especially single page applications, which are almost the only means of communicating with the server, and performing Ajax typically has the following steps:
At the client, you need to provide a URL, select a method to communicate with the server (Get,post,put,delete). The callback function is executed after the request is completed, the request result can be more success or failure, you need to give a hint when you fail, and you need to perform the action according to the return value when you succeed. Typically, at the start of a request, you need to give a busy wait (such as a page cover) that is being processed or related, and then recover when the request is completed.
When the server receives the request, it verifies the request parameters, executes the service-side code, and if an error or validation fails, give specific reasons and return the data that the client wants when it succeeds.
The ABP server supports standard AJAX request/output. We recommend that you use the Ajax request method provided in Abp.jquery.js, this method is based on the Ajax method of jquery, can automatically handle the exception information of the server, of course, if you are proficient in JS, you can also write Ajax according to your own needs.
asp.net boilerplate Ajax Request instance:


Construct the Parameter object to transfer
var Newperson = {
  name: ' Dougles Adams ',
  age:42
};
Invoke ABP Ajax method
abp.ajax ({
  URL: '/people/saveperson ',
  data:JSON.stringify (Newperson)//Convert to JSON string
}). Done (the function (data) {
abp.notify.success (' created new person with id = ' + data.personid ');
});



You can also use jquery's Ajax method calls, but you need to set the default request parameters, DataType is set to ' JSON ', the type is set to ' POST ' and contentType set to ' Application/json, When sending a request to convert a JS object to a JSON string, as with $.ajax, you can also pass parameters to override abp.ajax default parameters Abp.ajax return a promise type, you can programmatically write the following method:


. Done ()//success,
. FAIL ()//failure,
. Then ()//callback nesting.


The following simple example shows the Saveperson method of Ajax request Peoplecontroller, in. Done () to obtain the record ID returned when the server-side creation record succeeds.


public class Peoplecontroller:abpcontroller
{
  [httppost] public
  jsonresult Saveperson (Savepersonmodel person) {//todo:save The new person to
    database and returning new person ' s ID
//todo: Creates a new person record and returns the Idreturn Json (New {PersonId =});
  }



Savepersonmodel contains attributes such as Name,age. The HttpPost attribute Abp.ajax is marked on the Saveperson by default as a POST mode request. The return value is simplified to an anonymous object.



Savepersonmodel contains attributes such as Name,age. The HttpPost attribute Abp.ajax is marked on the Saveperson by default as a POST mode request. The return value is simplified to an anonymous object.



Ajax return value (Ajax returns messages)



We returned an anonymous object directly, ABP the return value through the Mvcajaxresponse type. The actual return value type is as follows:


{
 "Success": true,//correct handling flag
 "result": {
  "personId": 42//Returned data
 },
 "error": null,//If an error occurs, Result is null, this is the object of the error message, contains the messages and details two property
 "TargetUrl": null,//can provide a URL for client redirection, such as automatically build the next page URL
 " Unauthorizedrequest ": false//Whether authorization is passed, and if true, the client should log back in
}



If you inherit the object returned by the Abpcontroller,json method will always be wrapped in this way, if there is no error, you are in Abp.ajax's done (function (Result,data) {}), the first argument result is {" PersonId ": 42} object, data is the original object, Webapi inheritance Abpapicontroller 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! ",//Not caught exception, usually system exception, will automatically log, specific hint information in configuration file configuration, you can search, If it is the userfriendlyexception exception that is thrown by the business, the message is specific error information
  "Details": "..." The Abp.message.error function is invoked by default when an exception occurs, and you can modify it in Abp.jquery.js to handle the error message uniformly.
 },
 "Unauthorizedrequest": false
}



Dynamic Webapi (active Web API Layer)



The WEBAPI call function is dynamically generated here based on services:





Usually we use Ajax to do a simple encapsulation to reuse Ajax, where the framework can help you generate a simple invocation method
var Saveperson = function (person) {return
  Abp.ajax ({
    URL: '/people/saveperson ',
    data:JSON.stringify (person)
  };
Call when you need to construct
the parameter var Newperson = {
  name: ' Dougles Adams ',
  age:42
};
Direct call method, how to generate the above call method can refer to the source code in the ABP.WEB.API project/Webapi/controllers/scripting/jquery under the implementation of
Saveperson (Newperson). Done (the function (data) {
  abp.notify.success (' created new person with id = ' + data.personid ');
});




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.