ABP Presentation layer--javascript function library

Source: Internet
Author: User
Tags toastr

ABP Presentation layer--javascript function library

Click here to go to the ABP series articles General Catalogue

DDD-based Modern ASP.--ABP Series 21, ABP presentation layer--javascript function library

The ABP is "ASP. Boilerplate Project (ASP. NET Template project) "for short.

ABP's official website : http://www.aspnetboilerplate.com

ABP's Open source project on GitHub : https://github.com/aspnetboilerplate

The JS Library of the ASP. NET boilerplate provides some methods and objects for making JavaScript easier to develop, and the following is a list of the APIs in the library.

Ajax

Modern applications often use AJAX, especially single-page applications, which are almost the only means of communicating with a server, and performing Ajax typically has the following steps:

On the client side, you need to provide a URL to select a method for communicating with the server (Get,post,put,delete). The callback function executes after the request is completed, the request result can be more successful or failed, you need to give a hint when it fails, and you need to perform the action based on the return value when you succeed. Typically, at the start of a request, you need to give a busy wait message, such as a page overlay, that is similar to being processed or related, and resume after the request is complete.

After the server receives the request, validates the request parameters, executes the service-side code, and, if an error occurs or fails the validation, it should give a specific reason to return the data the client wants when it succeeds.

The ABP service side supports standard AJAX requests/outputs. We recommend that you use the Ajax request method provided in Abp.jquery.js, which is based on the Ajax method of jquery, can automatically handle the service side of the exception information, of course, if you are very skilled in JS, you can also write Ajax according to your own needs.

An example of an AJAX request for ASP. Boilerplate:

Build the Parameter object to transfer var Newperson = {    name: ' Dougles Adams ',    age:42};//calls the ABP's 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 jquery's Ajax method call, but you need to set the default request parameters, DataType set to ' JSON ', type set to ' POST ' and contentType set to ' Application/json, When sending a request, you need to convert the JS object to a JSON string, like $.ajax, you can pass the parameter overrides abp.ajax default parameters Abp.ajax return a promise type, you can chain programming to write the following method:

. Done ()//succeeded,. Fail ()//failed,. Then ()//callback nested.

A simple example below shows the Saveperson method of the AJAX request Peoplecontroller, which in. done () can get the record ID returned after the server-side creation record succeeds.

public class peoplecontroller:abpcontroller{    [HttpPost] public    jsonresult Saveperson (savepersonmodel person    {        //todo:save new person to database and return new person ' s Id//todo: Creates a new person record and returns the ID of this record return        Json ( new {PersonId = n});}    }

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

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

Ajax return value (Ajax returns messages)

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

{  "Success": true,//correctly handle flag  "result": {    "personId": 42//Data returned  },  "error": null,//If an error occurs, Result is null, this is an object of error information, contains a message and details two properties  "TargetUrl": null,//can provide a URL for client redirection, such as the URL to automatically build the next page  " Unauthorizedrequest ": false//Whether the 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 like this, if the error does not occur, you in Abp.ajax's done (function (Result,data) {}), the first parameter of the result is {" PersonId ": 42} object, data is the original object, and Webapi inherits Abpapicontroller is the same mechanism.

Error handling (Handling Errors)

The return values are 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 logs, specific information in configuration file configuration, you can search for a bit, If the userfriendlyexception exception is thrown by the business, the message is specific error message    "Details": "..."// When an exception occurs, the Abp.message.error function is called by default, and you can modify it in Abp.jquery.js to handle the error message uniformly.  },  "Unauthorizedrequest": false}
Dynamics WEBAPI (Dynamic Web API Layer)

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

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

Notifications appear in the lower right corner and disappear automatically later

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 dependent on the TOASTR library, you need to reference Toastr JS and CSS in your project, and then reference the abp.toastr.js,notify.success of the ABP project after the call looks like:

You can run a boilerplate project, test these tips in the console of your browser, and, when Ajax is an exception, you can modify the source file of the Abp.jquery.js to invoke the Abp.notify.error method to implement a friendly hint message.

If you have other notifications plug-ins can also be used, reference the corresponding JS library can be, the message JS is optional.

News

Used to display the dialog box to the user, display the message or get the user's confirmation, the ABP defaults to the Sweetalert Library implementation of the dialog box information, use you need to refer to the Sweetalert style and JS, and referencing Abp.sweet-alert.js, you can use the following APIs:

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 ');

Calling Abp.message.success will show the following dialog box:

Confirmation Confirmation dialog box:

Abp.message.confirm (    ' User admin will be deleted. ',//Confirm prompt    ' is you sure? ',//Confirm prompt (optional parameter)    function ( isconfirmed) {        if (isconfirmed) {            //...delete user clicks confirm after        }    });

The default ABP's JS library may refer to the message API, such as the failure of an Ajax call to invoke Abp.message.error.

Busy tips for the user interface

The ABP provides a busy API for setting up a section of the page.

UI Block API

Set up a translucent layer that prevents clicking on the page element and can overwrite the partial or entire page, as in the following example:

Abp.ui.block (); Covers the entire page Abp.ui.block ($ (' #MyDivElement ')); Overriding the specified element, the jquery object can be abp.ui.block as a parameter (' #MyDivElement '); or directly using the selector parameter Abp.ui.unblock (); The entire page is overwritten abp.ui.unblock (' #MyDivElement '); Specify an element to override

The UI Block API uses Blockui this JS library to achieve the effect, if you use this API need to refer to the Blockui JS Library and Abp.blockUI.js files on the page.

The UI Busy API indicates that the page is busy with APIs such as AJAX requests:

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

The first parameter can be used directly with the jquery selector such as ' #id ' or using a jquery object such as $ (' #id ') if NULL is passed or ' Body ' marks the entire page as busy, and the second parameter can receive a promise,promise after the completion of the page will automatically release the busy state.

Abp.ui.setBusy (    $ (' #MyLoginForm '),     Abp.ajax ({...})   The return value is promise, if you need more information about promise, you can refer to the Deferred of jquery);

The UI Busy API uses spin.js, and you need to refer to Spin.js and abp.spin.js in the page.

JS Log Interface

This is mainly for the browser console.log (' ... ') to carry out the packaging, can support all browsers, examples are as follows:

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

You can set the Abp.log.level to control the log output, as with the server, such as the setting of Abp.log.levels as info will not output the debug log, you can also customize according to your needs to re-API.

JavaScript public methods

The ABP provides a number of common public methods.

Create a namespace alias (Abp.utils.createNamespace)

By creating namespaces to make the JS method more specific and easier to use, here are some examples:

Create or get namespace Abp.utils = Abp.utils | | {};abp.utils.strings = Abp.utils.strings | | {};abp.utils.strings.formatting = abp.utils.strings.formatting | | {};//adds a method to the namespace Abp.utils.strings.formatting.format = function () {...}; You can create a namespace alias as follows: var formatting = abp.utils.createNamespace (ABP, ' utils.strings.formatting ';//Added under Formatting namespace) /Modify a method Formatting.format = function () {...};

Aliases simplify the previous long name, note that the first parameter is the root namespace that must exist.

Formatted string (abp.utils.formatString)

and a C # string. Format-like usage

ABP Presentation layer--javascript function library

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.