ABP (modern ASP. NET template Development Framework) Series 21, ABP presentation layer--javascript function library

Source: Internet
Author: User
Tags toastr

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 a Parameter object to transfer   newperson = ' dougles Adams '  //  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:

// Success, // failure, // callback nesting. 

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: Create a new person record and return the ID        of this record return Json (new);}    }

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 , // " result ": {" personId " : //  data returned   ", " error ": null , //  "TargetUrl": null ,  "unauthorizedrequest": false  //  If authorization is passed, and if true, the client should log on again } 

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": Span style= "color: #0000ff;" >false , //  represents an exception  "error" : { "message": "An internal error occured during your request!", //  The exception that is not caught, usually a system exception, automatically logs the log, the specific information in the configuration file configuration, you can search, if the business throws the userfriendlyexception exception, message for the specific error message  "Details": "..." //  " unauthorizedrequest ": false    
Dynamics WEBAPI (Dynamic Web API Layer)

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

//often we use Ajax to make a simple package to reuse Ajax as follows, where the framework can help you build a simple calling methodvarSaveperson =function(person) {returnabp.ajax ({URL:'/people/saveperson ', data:JSON.stringify (Person)});};//call when you need to build parametersvarNewperson ={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 implementationSaveperson (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 (    // confirmation prompt    ' is you sure? ',// confirmation prompt (optional parameter)    function  (isconfirmed) {        if  (isconfirmed) {            // ... delete user clicks confirm to execute         }    });

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:

// Overwrite entire page // overrides the specified element, you can use the jquery object as a parameter // or use selector parameters directly // Overwrite entire page // 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 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 | |  {};  //  Abp.utils.strings.formatting.format = function   () {...}; You can use the  //  Create a namespace alias  var  formatting = abp.utils.createNamespace (ABP, ' utils.strings.formatting ' ;  //  Formatting.format =  () {...}; 

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

var // str = ' Hello world! ' var // str = ' Secret number is '

I hope that more domestic architects will be able to focus on the ABP project, and perhaps it will help you, perhaps with your participation, this project can develop better.

Welcome to add ABP Architecture Design Exchange QQ Group: 134710707

Click here to go to the ABP series articles General Catalogue

ABP (modern ASP. NET template Development Framework) Series 21, 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.