& Lt; ABP document & gt; Javascript Api, abpapi

Source: Internet
Author: User
Tags types of functions

<ABP document> Javascript Api, abpapi

Content of this section:

  • AJAX Operation Problems
  • ABP Method
    • AJAX return information
    • Handling error
      • HTTP status code
    • WrapResult and DontWrapResult features
      • Asp.net Mvc Controller
      • Asp.net Web Api Controller
      • Dynamic Web Api Layer
      • Asp.net Core controller
    • Dynamic Web Api Layer

 

AJAX Operation Problems

Executing an AJAX call is very common in today's Applications. Especially in SPAs (Single-Page Applications Single-Page application), it is almost the only way to communicate with the server. An AJAX call consists of several repeated steps:

On the client, basically, javascript code should provide a URL, random data and select a method (POST, GET ...) to execute an AJAX call, it must wait for and process the returned value. When you execute a call to the server, it may cause errors (usually network errors) or other server errors, the server returns a response that contains an error message. The client should process the response or notify the user (an error dialog box can be displayed). If there is no error, the server sends a response, the client must also process it. During the operation, the screen is usually blocked or the whole screen is displayed and an AJAX operation information is displayed until it is completed.

The server code obtains a request, executes some server code, captures any exceptions, and returns a valid response to the client. If an error occurs, an error message may be sent to the client. If a verification error occurs, the server may add a verification problem. If successful, a return value may be sent to the client.

 

ABP Method

The following is an example of AJAX call:

var newPerson = {    name: 'Dougles Adams',    age: 42};abp.ajax({    url: '/People/SavePerson',    data: JSON.stringify(newPerson)}).done(function(data) {    abp.notify.success('created new person with id = ' + data.personId);});

Abp. ajax gets an optional object, and you can pass any parameter (it will be $. ajax verification). Here some default values are: dataType: 'json', type: 'post', contentType: 'application/json' (therefore, before sending the data to the server, we call json. stringify converts javascript to a JSON string. ajax passes options to override these default values.

Abp. ajax returns promise, so you can write done, fail, then .... processing program. In this example, we create a simple AJAX request and call the SavePerson operation of eaglecontroller. In the done processing program, we get the id of the newly created person in the database and display a successful notification (view notification API ). Let's take a look at the MVC Controller called by AJAX:

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

The SavePersonModel contains the Name and Age attributes, and the SavePerson flag is HttpPost. Therefore, the default method of abp. ajax is POST. The implementation of the simplified method returns only one anonymous object.

This is straightforward, but some important items are handled behind the scenes, allowing us to go into details...

 

AJAX return information

Even if we return a PersonId = 2 object, the ABP wraps it into an MvcAjaxResponse object, and the AJAX response is essentially like the following:

{  "success": true,  "result": {    "personId": 42  },  "error": null,  "targetUrl": null,  "unAuthorizedRequest": false,  "__abp": true}

Here, all attributes are named by Xiao luofeng (because this is agreed in the javascript World), even if they are named by da luofeng on the server side. Let's explain these attributes:

  • Success: A boolean value (true or false) that indicates whether the operation is successful. If it is true. ajax solution board promise and call the done handler. If it is false (if an exception is thrown in a method call), it calls the fail handler and uses the abp. message. the error function displays error information.
  • Result: return the operation result in the Controller. If success is set to true, the server sends a returned value before it is available.
  • Error: If success is false, this attribute contains an object with error details.
  • TargetUrl: provide a URL to the server. When necessary, direct the client to this URL.
  • UnAuthorizedRequest: the service end sends a notification to the client: the operation is not authenticated or the user is not authenticated. If this parameter is set to true, ABC. ajax reloads the current page.
  • _ Abp: A special identifier, indicating that the response is packaged with an ABC. You do not need to use it, and the ABP. ajax will process it.

If there is no error, your done handler in the abp. ajax gets the true controller return value (an object containing the personId attribute ).

 

Handling error

As mentioned above, an object containing the error message is returned when an ABC exception is handled on the server:

{  "targetUrl": null,  "result": null,  "success": false,  "error": {    "message": "An internal error occured during your request!",    "details": "..."  },  "unAuthorizedRequest": false,  "__abp": true}

As you can see, if success is false and result is null, an error message is displayed to the user by processing this object using the abp. message. error function. If the server throws a userFriendlyException type exception, it displays the error message to the user directly. Otherwise, it hides the actual error (writes the error to the log) and displays an "internal error occurred... "the information is sent to the user, and these abcws are automatically processed.

You may want to disable display of information for some specific AJAX calls. In this case, you can add abpHandleError: false to the options of abp. ajax.

 

HTTP status code

The given status code is returned for an exception:

  • 401 is an unauthenticated request (the user has not logged on, but the server needs to authenticate the operation ).
  • 403 is an unauthorized request.
  • 500 for all other types of exceptions.

 

WrapResult and DontWrapResult features

You can control the packaging by using the WrapResult and DontWrapResult features for one operation or all operations of the controller.

 

Asp.net Mvc Controller

If the return type of Asp.net Mvc operation method is JsonResult (or asynchronous Task <JsonResult>), it is packaged by default (as described above). You can use the WrapResult feature to change this behavior, as follows:

public class PeopleController : AbpController{    [HttpPost]    [WrapResult(WrapOnSuccess = false, WrapOnError = false)]    public JsonResult SavePerson(SavePersonModel person)    {        //TODO: save new person to database and return new person's id        return Json(new {PersonId = 42});    }}

As a shortcut, we can only use [DontWrapResult] to achieve the same purpose as this example.

You can change the default behavior from the startup Configuration (using Configuration. Modules. AbpMvc.

 

Asp.net Web Api Controller

By default, the result of successful Web Api operations is not packaged. If necessary, you can add the WrapResult to the operation or controller, but the default packaging is abnormal.

You can change the default behavior from the startup Configuration (using Configuration. Modules. AbpWebApi.

 

Dynamic Web Api Layer

By default, you can use the WrapResult and DontWrapResult features on your application service interface to modify the Method Results of the dynamic Web Api layer.

 

Asp.net Core controller

ABC automatically wraps JsonResult, ObjectResult, and any results without IActionResult. For more information, see Asp.net Core.

You can change this default behavior from the startup Configuration (using Configuration. Modules. AbpAspNetCore.

 

Dynamic Web Api Layer

Although it provides a simple AJAX mechanism, writing a javascript function for each AJAX call is typical in a real-world application, for example:

//Create a function to abstract AJAX callvar 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);});

Writing a function for each AJAX call is a good practice, but it is time-consuming and boring. The ABP can automatically generate these types of functions for the Application Service and controller.

Go to the dynamic Web Api layer documentation for more Web Api information, and view the Asp.net Core documentation for information on Asp.net Core integration.

 

Kid1412 Appendix: http://www.aspnetboilerplate.com/Pages/Documents/Javascript-API/AJAX

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.