Abp-javascript API (GO)

Source: Internet
Author: User
Tags toastr

Transferred from: http://www.cnblogs.com/zd1994/p/7689164.html

For the regular use, for reference

First, AJAX

The way 1,ABP is used

The ASP. NET boilerplate automatically executes some of these steps by wrapping the Ajax callback with the Abp.ajax function. An example of an Ajax call:

var Newperson = {    name: ' Dougles Adams ',    age:42};abp.ajax ({    URL: '/people/saveperson ',    data: Json.stringify (Newperson)}). Done (the function (data) {    abp.notify.success (' created new person with id = ' + Data.personid);});

Abp.ajax takes an object as the Receive option . You can pass any parameters that are valid in the jquery $.ajax method. Here are some default values: DataType is ' json ', type is ' POST ', contenttype is ' Application/json ' (so we can call JSON before sending it to the server.) Stringify the JavaScript object into a JSON string). You can override the default value by passing the option to Abp.ajax.

Abp.ajax returned to the promise. Therefore, you can write done,fail,then and other processing functions. In the example above, we sent a simple Ajax request to Peoplecontroller's Saveperson action. In The done handler, we get the database ID of the newly added person and show a successful notification. Let's take a look at the MVC controller for the AJAX request

public class peoplecontroller:abpcontroller{    [HttpPost] public    jsonresult Saveperson (savepersonmodel person    {        //todo: Saves the new person to the database and returns the ID of the person return        Json (new {PersonId =);}    }

Savepersonmodel contains the name and age properties. The Saveperson tag has the HttpPost attribute because the Abp.ajax default method is post. This simplifies the implementation of the method by returning an anonymous object.

2,ajax return message
Even if we return the object PersonID = 2 directly, the ASP. NET boilerplate is also wrapped by the Mvcajaxresponse object. The actual AJAX response is this:

{  "Success": true,  "result": {    "personId": "$"  ,  "error": null,  "TargetUrl": null,  " Unauthorizedrequest ": false}

Here, all the properties are CamelCase (because this is customary in JavaScript), even if it is pascalcased in the service-side code. Here's an explanation of all the fields:

    • Success: A Boolean value that represents the success status of the operation. If it is True,abp.ajax will parse the promise and call the done handler function. If it is false (if an exception occurred in the method call), it invokes the fail handler and uses the Abp.message.error function to present an error message.
    • result: The actual value returned by the Controller's action. If success is true, and the server sends a return value, it is valid.
    • Error: If success is false, then the field is an object containing the message and detail fields.
    • TargetUrl: This provides a possibility for the server to redirect clients to other URLs.
    • unauthorizedrequest: This provides the server with the possibility to notify the client that the operation is not authorized or that the user does not have authentication. If the value is true, then Abp.ajax reloads the current page.

By deriving from the Abpcontroller class, you can convert the return value into an encapsulated AJAX response. Abp.ajax will recognize and calculate the response. As a result, they work in pairs. If there is no error, then the Abp.ajax done handler will get the actual value returned by the controller (an object with the PersonID property).

The same mechanism also exists when deriving from the Abpapicontroller class.

3, Handling Errors

As described above, the ABP handles all exceptions on the server and returns an object with error information, as follows:

{  "TargetUrl": null,  "result": null,  "Success": false,  "error": {    "message": "An internal error occured during your request! ",    " Details ":" ... "  },  " Unauthorizedrequest ": false}

As you can see, success is False,result is null. Abp.ajax handles the object, and uses the Abp.message.error function to present an error message to the user. If your service-side code throws an exception of type userfriendlyexception , it will display the exception information directly to the user. Otherwise, it hides the actual error (writes the error to the log) and presents a standard "server internal error ..." message to the user. All of this is handled automatically by the ABP.

4, Dynamic Web API layer

Although the ABP provides a simple mechanism for invoking Ajax, in real-world applications it is classic to write JavaScript functions for each Ajax call, such as:

Create an abstract Ajax call to Functionvar Saveperson = function (person) {    return Abp.ajax ({        URL: '/people/saveperson ',        data:JSON.stringify (person)    });};/ /Create a new Personvar Newperson = {    name: ' Dougles Adams ',    age:42};//Save the Personsaveperson (Newperson). Done ( function (data) {    abp.notify.success (' created new person with id = ' + data.personid);});

Second, Notification

Show notifications for auto-off.

We like to show some fine auto-disappearing notifications when something happens, such as when a record is saved or when a problem occurs. The ABP defines the standard APIs for this.

Abp.notify.success (' A message text ', ' optional title '); Abp.notify.info (' A message text ', ' optional title '); Abp.notify.warn (' A message text ', ' optional title '); Abp.notify.error (' A message text ', ' optional title ');

The notification API is implemented by default using the toastr Library. For toastr to take effect, you should refer to Toastr's CSS and JavaScript files, and then include Abp.toastr.js as the adapter in the page. A TOASTR success notification is as follows:

You can also use your favorite notification library to implement notifications. Just rewrite all the functions in the custom JavaScript file and add it to the page instead of abp.toastr.js (you can check the file to see if it's implemented, which is pretty straightforward).

Third, Message

Displays the message dialog box to the user.

The message API is used to present messages to the user or to obtain confirmation from the user.

The message API is implemented by default using Sweetalert . For Sweetalert to take effect, you should include its CSS and JavaScript files, and then add the abp.sweet-alert.js reference to the page as the adapter.

Abp.message.info (' Some info message ', ' some optional title '); Abp.message.success (' Some success message ', ' some optional Title '); Abp.message.warn (' Some warning message ', ' some optional title '); Abp.message.error (' Some error message ', ' some Optional title ');

A successful message is as follows:

Abp.message.confirm (    ' User admin'll be deleted. ',    ' is you sure? ',    function (isconfirmed) {        if ( isconfirmed) {            //... Delete User        }    });

The second argument (title) Here is optional, so the callback function can also be the second parameter.

An example of a confirmation message is as follows:

The message API is used internally by the ABP. For example, if the AJAX call fails, it will call Abp.message.error.

Iv. UI block and busy API

Use an area (a div,form, an entire page, and so on) to block the user's input. In addition, a zone is busy (with a busy indicator, such as ' Loading ... ').

1,ui Block API

The API uses a transparent coating (transparent overlay) to block the entire page or an element on the page. This way, the user's click is not valid. This is useful when saving a form or loading an area (a div or an entire page), such as:

Abp.ui.block (); Block the entire page abp.ui.block ($ (' #MyDivElement ')); You can use the jquery selector: Abp.ui.block (' #MyDivElement '); //.. or directly using the selector abp.ui.unblock (); Unblock entire page abp.ui.unblock (' #MyDivElement '); Unblocking a specific element

The UI Block API is implemented by default with jquery's Blockui plugin. If it comes into effect, you should include its JavaScript file, and then include Abp.blockUI.js as the adapter in the page.

2,ui Busy API

This API is used to make certain pages or elements busy. For example, you might want to block a form and then show a busy indicator when submitting the form to the server. Example:

Abp.ui.setBusy (' #MyLoginForm '); Abp.ui.clearBusy (' #MyLoginForm ');

The parameter should be a selector (such as ' #MyLoginForm ') or a jquery selector (such as $ (' #MyLoginForm ')). To make the entire page busy, you can pass in null (or ' body ') as a selector.

The second parameter of the SETBUSY function receives a promise (contract) that automatically clears the busy state when the contract is completed. Example:

Abp.ui.setBusy (    $ (' #MyLoginForm '),     Abp.ajax ({...})   );

Because Abp.ajax returns promise, we can pass it directly as a promise. To learn the habit of promise more things, check out the Deferredof jquery.

The UI Busy API is implemented using spin.js . For it to take effect, it should contain its JavaScript file and then include Abp.spin.js as the adapter in the page.

V. Event Bus

The global event used to register and trigger the client.

The pub/sub event model is widely used by clients, and the ABP contains a simple global event bus to register and trigger events .

1, registering events

You can use Abp.event.on to register a global event. An example of a registration:

Abp.event.on (' Itemaddedtobasket ', function (item) {    Console.log (Item.name + ' is added to basket! ');});

The first parameter is the unique name of the event . The second is the callback function, which is called when a particular event is triggered.

You can use the Abp.event.off method to unregister from an event. Note: To unregister, provide the same function. Therefore, for the above example, you should set the callback function to a variable and then use it in the on and off methods.

2, triggering event

The Abp.event.trigger is used to trigger a global event. The code for triggering an already registered event is as follows:

Abp.event.trigger (' Itemaddedtobasket ', {    id:42,    name: ' Acme light mousepad '});

The first parameter is the unique name of the event . The second is an (optional) event argument . You can add any number of parameters and get them in the callback method

Vi. Log

Logs are logged on the client.

1,javascript Logging API

When you want to log some simple logs on the client, you can use the Console.log (' ... ') API, which you already know. However, this is not supported by all browsers and may corrupt your script. Therefore, you should first check that the console is available, in addition, you may want to record logs elsewhere, even if you want to log at some level. The ABP defines a secure log function:

Abp.log.debug (' ... '); Abp.log.info (' ... '); Abp.log.warn (' ... '); Abp.log.error (' ... '); Abp.log.fatal (' ... ');

Vii. Other tool skills

ABP provides a number of common tool functions.

1,abp.utils.createnamespace

Used to create a deeper namespace immediately. Suppose we have a base namespace ' ABP ' and then want to create or get the ' abp.utils.strings.formatting ' namespace

var formatting = abp.utils.createNamespace (ABP, ' utils.strings.formatting ';// Add a Functionformatting.format = function () {...} to the namespace;

This simplifies the creation of deep namespaces in a secure manner. Note that the first parameter is a root namespace that must exist.

2,abp.utils.formatstring

This and the string in C #. Format () is similar. Usage examples:

var str = abp.utils.formatString (' Hello {0}! ', ' world '); str = ' Hello world! ' var str = abp.utils.formatString (' {0} number is {1}. ', ' Secret ', 42); str = ' Secret number is 42 '

Abp-javascript API (GO)

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.