In Part 3, 01, we write methods in web services, but we usually write some methods in the. CS file on the page. So how can we use JavaScript to call these methods asynchronously? The solution is provided below
One default. aspx. CS
Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. Web. Services;
Public partial class _ default: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
}
[Webmethod]
Public static string sayhellofrompage (string strname)
{
Return string. Format ("Hello {0 }! ", Strname );
}
}
II default. aspx
<% @ Page Language = "C #" autoeventwireup = "true" codefile = "default. aspx. cs" inherits = "_ default" %>
<! Doctype HTML public "-// W3C // dtd xhtml 1.1 // en" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> untitled page </title>
<Script language = "JavaScript" type = "text/JavaScript">
Function callservice ()
{
VaR name = $ get ("text1"). value;
Pagemethods. sayhellofrompage (name, onsayhellosucceeded );
}
Function onsayhellosucceeded (result)
{
$ Get ("result"). innerhtml = result;
}
</SCRIPT>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Asp: scriptmanager id = "scriptmanager1" runat = "server" enablepagemethods = "true">
</ASP: scriptmanager>
<Div id = "div1">
<Input id = "text1" type = "text"/>
<Input id = "button1" type = "button" value = "Say hello" onclick = "callservice ()"/>
<Div id = "result"> </div>
</Div>
</Form>
</Body>
</Html>
Summary
1. Set the attribute enablepagemethods of scriptmanager to true.
2. Use the following JavaScript syntax on the client to call the PAGE method:
Pagemethods. [methodname] (param1, param2 ..., Callbackfunction)
3. The method must be declared as public static.
4. Add the using system. Web. Services namespace;
5. Add [webmethod] to the Method
4. References
Http://www.cnblogs.com/dflying/archive/2007/06/05/771490.html