Asp.net Ajax WebService development documentation classification: javascript. Net ajax2009-02-11 750 people read comments (1)
Asp.net Ajax WebService development document
Basic usage
1. Create a new solution, right-click the solution name, select "Add-New Website", create an Asp.net website website1, right-click website1, and select "Add new project-web service ", add a Web Service webservice1. Generate webservice1.asmx in the following directory, and generate webservice1.cs in the app_code folder. In the webservice1.cs file, a web method helloworld has been generated as follows:
/// <Summary>
/// Return a string
/// </Summary>
/// <Returns> </returns>
[Webmethod]
Public String helloworld ()
{
Return "Hello World ";
}
Note: The [system. Web. Script. Services. scriptservice] commented out will be removed.
2. Create a web form and add the scriptmanage component. The configuration is as follows:
<Asp: scriptmanager id = "scriptmanager1" runat = "server">
<Services>
<Asp: servicereference Path = "~ /Webservice1.asmx "/>
</Services>
</ASP: scriptmanager>
The method for calling this web service in JS is:
WebService. helloworld (function sucess (RES) {alert (RES );},
Function failed (RES) {alert (RES );},
"Calling web services ");
3. Use the web method to return a single JSON object
Create a new student class that contains three attributes: sname, ssex, and iage. Create the following method in the webservice1.cs file:
...
Using system. Web. Script. Services;
...
/// <Summary>
/// Return a single JSON object
/// </Summary>
/// <Returns> </returns>
[Webmethod]
[Scriptmethod (responseformat = responseformat. JSON)]
Public student showinfo ()
{
Return new student ("zww", "man", 26 );
}
[Scriptmethod (responseformat = responseformat. JSON)] serializes the student object into a JSON object so that JavaScript operations can be performed on the page.
The Web Service is used on the page as follows:
WebService. showinfo (function (RES)
{
If (RES = NULL) return;
Alert (res. sname );
});
Note: the conversion between JSON objects and JSON strings is as follows,
WebService. showinfo (function (RES)
{
If (RES = NULL) return;
// Serialize the JSON object into a string
VaR personstr = SYS. serialization. javascriptserializer. serialize (RES );
Alert (personstr); // {"_ type": "student", "sname": "zww", "ssex": "Man", "iage ", "26 "}
// Deserializes a string into a JSON object
VaR person = SYS. serialization. javascriptserializer. deserialize (personstr, true );
Alert (person); // [object]
// The JSON object passed from WebService is directly accessed using "Object Name. attribute name"
Alert (res. sname); // zww
// Var STR = '{name: "zww", sex: "Man", color: "yellow "}';
// Var person = eval ('+ STR + ')');
});
4. Use the web method to return a single JSON object (using the list container)
...
Using system. Web. Script. Services;
...
/// <Summary>
/// Return multiple JSON objects
/// </Summary>
/// <Returns> </returns>
[Webmethod]
[Scriptmethod (responseformat = responseformat. JSON)]
Public list <student> getall ()
{
List <student> List = new list <student> ();
Student S1 = new student ("Tom", "man", 26 );
Student S2 = new student ("Mary", "Woman", 22 );
List. Add (S1 );
List. Add (S2 );
Return list;
}
The Web Service is used on the page as follows:
// Operation: List container object for storing specific objects
WebService. getall (function (RES)
{
If (RES = NULL) {return ;}
VaR content = "";
For (VAR I = 0; I <res. length; I ++)
{
Content = content + Res [I]. sname + "<br/> ";
}
Document. getelementbyid ("info"). innerhtml + = content;
});
5. Use a custom serialization method (convert a data record able to a JSON object)
The class that converts a able to a JSON object is as follows:
Using system;
Using system. Collections. Generic;
Using system. collections;
Using system. Data;
Using system. Web. Script. serialization;
/// <Summary>
/// Summary of myjsons
/// </Summary>
Namespace zww. Utility
{
Public class datatableconverter: javascriptconverter
{
Public override ienumerable <type> supportedtypes
{
Get
{
Return New Type [] {typeof (datatable )};
}
}
Public override object deserialize (idictionary <string, Object> dictionary, type, javascriptserializerserializer)
{
Throw new notimplementedexception ();
}
Public override idictionary <string, Object> serialize (Object OBJ, javascriptserializer serializer)
{
Datatable listtype = OBJ as datatable;
If (listtype! = NULL)
{
// Create the representation.
Dictionary <string, Object> result = new dictionary <string, Object> ();
Arraylist itemslist = new arraylist ();
Foreach (datarow row in listtype. Rows)
{
// Add each entry to the dictionary.
Dictionary <string, Object> listdict = new dictionary <string, Object> ();
Foreach (datacolumn DC in listtype. columns)
{
Listdict. Add (DC. columnname, row [DC]);
}
Itemslist. Add (listdict );
}
Result ["rows"] = itemslist;
Return result;
}
Return new dictionary <string, Object> ();
}
}
}
Store these files in the app_code folder and add the following items to the Web. config file:
<System. Web. Extensions>
<Scripting>
<WebServices>
<Jsonserialization maxjsonlength = "1024000">
<Converters>
<Add name = "datatableconverter" type = "zww. Utility. datatableconverter"/>
</Converters>
</Jsonserialization>
</WebServices>
</Scripting>
</System. Web. Extensions>
Create the following method in webservice1.cs:
[Webmethod]
[Scriptmethod (responseformat = responseformat. JSON)]
Public datatable queryall ()
{
Return dB. queryall (). Tables [0];
}
The db. queryall () return type is dataset.
The method for calling this web service on the page is:
// Directly operate the JSON-formatted able
WebService. queryall (function (RES)
{
If (RES = NULL) {return ;}
VaR content = "";
For (VAR I = 0; I <res. Rows. length; I ++)
{
Content = content + res. Rows [I] ["code"] + "<br/> ";
}
Document. getelementbyid ("info"). innerhtml + = content;
});
Here we will introduce such a few points, and there are other more advanced usage methods that need to be learned slowly. If you have any mistakes, please correct them. Thank you.