Use ASP. Net ajax to asynchronously call the class methods in Web Services and pages (6): automatic conversion of server and client data types: complex types

Source: Internet
Author: User

This article is from ASP.. Net Ajax programming Chapter II: client-related Microsoft Ajax library Chapter III asynchronous call of Web Services and class methods on pages. For more information, see other articles in this chapter.

 

 

3.7.3Complex types

To pass some complex data types, such as a custom type or structure, we need to explicitly inform ASP. net Ajax asynchronous communication layer generates the corresponding client JavaScript type for the server type.

C #CodeThe description of the employee class can be considered as a "complex type". Let's take this employee class as an example to illustrate how to transmit complex types at the ASP. NET Ajax asynchronous communication layer:

 
Public ClassEmployee
 
{
 
Private IntM_id;
 
Public IntID
 
{
 
Get {ReturnM_id ;}
Set {m_id =Value;}
 
}
 
 
 
Private StringM_name;
 
Public StringName
 
{
 
Get {ReturnM_name ;}
 
Set {m_name =Value;}
 
}
 
 
 
Private StringM_email;
 
Public StringEmail
 
{
 
Get {ReturnM_email ;}
Set {m_email =Value;}
 
}
 
 
 
Private IntM_salary;
 
Public IntSalary
 
{
 
Get {ReturnM_salary ;}
 
Set {m_salary =Value;}
 
}
 
 
 
PublicEmployee ()
 
{
 
}
 
 
PublicEmployee (IntID,StringName,StringEmail,IntSalary)
 
{
 
M_id = ID;
 
M_name = Name;
 
M_email = Email;
 
M_salary = salary;
 
}
 
}

As you can see, this employee class contains four public attributes: ID, name, email, and salary, indicating the employee ID, name, email address, and salary respectively. In addition to the four public attributes, the employee class also provides two constructors. However, no method is defined (the so-called "degradation class ". The "degradation class" is similar to the struct to represent structured data ). This section and several subsequent sections will use this employee class. to deepen our impression, we provide a class diagram of the employee class, as shown in 3-16.

Note: If you want ASP. net Ajax asynchronous communication layer automatically generates the corresponding client version for the server type, so this type must provide a non-parameter constructor, all the public attributes of this class should provide getter and setter accessors. In addition, only the public attributes of the original server type are retained in the Client Version type Automatically Generated Based on the server type, the methods and private fields of the original type are not mapped to the client object (the public field is mapped to the client object ).

Figure 3-16 class diagram of the employee class

After learning about the employee class, let's use an exampleProgramThis section describes how to pass the employee type in the ASP. NET Ajax asynchronous communication layer. The first is the Web service code on the server, which defines two methods: createnewemployee () and saveemployee (). One employee object is returned or accepted respectively:

 
 
 
[WebService (namespace ="Http://tempuri.org /")]
 
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
 
[Generatescripttype (Typeof(Employee)]
 
[Scriptservice]
Public ClassPeoplemanagementservice: system. Web. Services. WebService
 
{
 
[Webmethod]
 
PublicEmployee createnewemployee ()
 
{
 
Return NewEmployee (0,String. Empty,String. Empty, 0 );
 
}
 
 
 
[Webmethod]
 
Public BoolSaveemployee (employee em)
 
{
 
// Save it to the database...
 
 
Return True;
 
}
 
}

The createnewemployee () and saveemployee () methods cannot complete any specific work. They only provide the demo function. The[Generatescripttype (typeof (employee)]Attribute (bold in the above Code) is the key to completing program functions. This attribute is defined in the namespace of system. Web. Script. Services. If we want ASP. net Ajax asynchronous communication layer generates the Javascript corresponding types of clients for a complex type, so as to complete the communication between the server and the client, the generatescripttype attribute should be explicitly declared.

Note: [generatescripttype (typeof ([typename])] attributes are not mandatory. However, if the complex types in the outermost layer are nested with complex types with an inner layer, for example, an attribute in the employee ID points to another complex type-Manager (this manager type is a nested complex type ), therefore, we must explicitly add the [generatescripttype (typeof ([Manager])] attribute to the web service. Or if the parameter or return value of a Web service method is list <employee> (which will be introduced later), we also need to add [generatescripttype (typeof ([employee])] for the web service. attribute.

Because of this complexity, we recommend that you use the [generatescripttype (typeof ([typename])] attribute in the Web service class for any complex types, to reduce the possibility of exceptions caused by carelessness. In addition, the [generatescripttype (typeof ([typename])] attribute can also be added to the web service method. The effect is the same as that added to the web service class.

Then add the scriptmanager control and reference of the corresponding web service on the ASP. NET page:

 
<ASP: scriptmanager ID= "SM" Runat= "Server">
 
<Services>
 
<ASP: servicereference Path= "Services/peoplemanagementservice. asmx" />
</Services>
 
</ASP: scriptmanager>

The UI code of the page is very intuitive:

 
<Label For= "Tbid">ID</Label> <Input ID= "Tbid" Type= "Text" /> <BR />
    label   for 
     = "tbname"    name    label     input   id   = "tbname"   type   =" text " />   Br  />  
    label   for   =" tbemail " > email    label  ><   input   id   = "tbemail"   type   = "text"  /> <  Br  />  
<Label For= "Tbsalary">Salary</Label> <Input ID= "Tbsalary" Type= "Text" /> <BR />
 
 
 
<Input ID= "Btnnew" Type= "Button" Value= "Create new" 
Onclick= "Return btnnew_onclick ()" />
 
<Input ID= "Btnsave" Type= "Button" Value= "Save" 
 
Onclick= "Return btnsave_onclick ()" />

The preceding four <input/> parameters are used to display the ID, name, email, and salary attributes of an employee object, and edit these attributes. The next two <input/> buttons call the client proxies of the createnewemployee () and saveemployee () methods defined in the previous Web Service respectively.

The btnnew_onclick () event processing function and the corresponding callback function are as follows:

 
FunctionBtnnew_onclick (){
Lelemanagementservice. createnewemployee (oncreated );
 
}
 
 
 
FunctionOncreated (result ){
 
Employeeinediting = result;
 
$ Get ("Tbid"). Value = maid. ID;
 
$ Get ("Tbname"). Value = maid. Name;
 
$ Get ("Tbemail"). Value = employeeinediting. Email;
 
$ Get ("Tbsalary"). Value = maid. salary;
 
}

Note that the result object in the callback function is the client type automatically generated by the C # employee class at the ASP. NET Ajax asynchronous communication layer. Figure 3-17 shows the structure of the result object (type: Employee) viewed in the Visual Studio debugger.

Figure 3-17 structure of the client's employee type

Tip: in actual development, we can also directly use the constructor of the client's employee class to construct an employee object on the client, instead of getting the new objects required by the program from the server, you can improve the overall performance of the application:

 
VaREm =NewEmployee ();

In the above Code, the employeeinediting is a global variable used to save the currently being edited client employee object, which is defined beyond these two functions:

 
VaREmployeeinediting =Null;

The callback function displays the four attribute values of the newly created employee object on the server in the four text boxes on the page for editing. See Figure 3-18.

Figure 3-18 after you click "create new", the program retrieves a new employee object from the server.

After editing the four entries, click "save" to trigger the btnsave_onclick () event handler. The btnsave_onclick () event processing function and the corresponding callback function are as follows:

 
FunctionBtnsave_onclick (){
 
Employeeinediting. ID = $ get ("Tbid"). Value;
Employeeinediting. Name = $ get ("Tbname"). Value;
 
Employeeinediting. Email = $ get ("Tbemail"). Value;
 
Employeeinediting. Salary = $ get ("Tbsalary"). Value;
 
 
 
Lelemanagementservice. saveemployee (employeeinediting, onsaved );
 
}
 
 
 
FunctionOnsaved (result ){
 
If(Result ){
 
Alert ("Employee saved! ");
 
}
 
}

Specifically, only the four attributes of the client employee object are updated, and then passed to the server through the ASP. NET Ajax asynchronous communication layer. Figure 3-19 shows the employee Object received by the saveemployee () method on the server side from the client.

Figure 3-19 the employee Object received by the saveemployee () method from the client

After the saveemployee () method is returned successfully on the server side, the onsaved () callback function of the client will pop up a prompt dialog box on the page. See Figure 3-20.

Figure 3-20 click "save" to save the program interface after the employee object

In some cases, we do not want to expose all the attributes of a server type to the client object. For example, for the salary attribute in the employee class, for some security or privacy considerations, we may want the asynchronous communication layer to automatically generate client objects (serialize them to JSON strings) this attribute is ignored, that is, only the ID, name, and email attributes are generated in the client object.

ASP. NET Ajax asynchronous communication layer can well support this requirement. All we need to do is to add the salary attribute in the employee class[System. Web. Script. serialization. scriptignore]Attributes. The modified salary attributes are as follows. Note the bold Section:

 
Private IntM_salary;
 
[System. Web. Script. serialization. scriptignore]
 
Public IntSalary
 
{
 
Get {ReturnM_salary ;}
Set {m_salary =Value;}
 
}

In this case, the client JavaScript type generated by the ASP. NET Ajax asynchronous communication layer for the employee class will no longer contain the salary attribute. Figure 3-21 shows the structure of the client employee type seen in the Visual Studio debugger.

Figure 3-21 structure of the client employee type after the salary attribute is ignored

Conclusion: To enable the ASP. Net Ajax asynchronous communication layer to automatically generate the corresponding client JavaScript type for the complex type on the server side, and pass and receive the complex type during the call process, we need:

    1. Add the [scriptservice] attribute to the methods that need to be exposed to the client in the Web service or web service;
    2. Add the [webmethod] attribute for the method that the Web Service needs to expose to the client;
    3. A parameter or return value of a method in the Web service class is of this complex type;
    4. Add several [generatescripttype (typeof ([typename])] attributes to the Web service class. [typename] indicates the name of the complex type or its nested complex type;
    5. A constructor without parameters is required for this complex type;
    6. All public attributes of this complex type should provide getter and setter accessors (that is, they must be readable and writable), unless in the following situations:
      1. [System. web. script. serialization. scriptignore] attribute, that is, Asp.. Net Ajax asynchronous communication layer ignores this attribute when generating the client JavaScript type, so its attribute can be no setter or getter.
      2. This server-side object is only used to output JSON strings in one way, so its attribute can be no setter.
      3. The value of this attribute is not set when the client passes in, so this attribute can have no setter.
    7. Add a reference to the Web service in the scriptmanager control on the page.

The ASP. NET Ajax asynchronous communication layer will:

    1. The public property or public field (field) of [system. Web. Script. serialization. scriptignore] is not applied to the client JavaScript type;
    2. Private fields of the complex type are not mapped to the Javascript type of the client;
    3. The method of this complex type is not mapped to the Javascript type of the client;

You can also use the following syntax to directly create the complex type on the client:

 
VaRMyobj =New[Namespace]. [classname] ();
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.