Client:
Copy codeThe Code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "ASP. NETA_JAX.aspx.cs" Inherits = "_ Default" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
<Script type = "text/jscript">
Function CallServer (){
// JSON sending object
ServerSum ("{name: 'linyijia ', age: '21 '}");
}
Function GetRegister (rg, contex ){
Document. getElementById ("TxtRegister"). value = rg;
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Br/>
Username: <input id = "TxtNum1" type = "text"/>
<Br/>
Server: <input id = "TxtRegister" type = "text"/> <br/>
<Button id = "SumBtn" type = "button" onclick = "CallServer ()"> log on </button>
</Div>
</Form>
</Body>
</Html>
Server:
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. Script. Serialization;
Public partial class _ Default: System. Web. UI. Page, ICallbackEventHandler
{
Users u = null;
Protected void Page_Load (object sender, EventArgs e)
{
// Call back the GetRegister Method
String CallBackFun = Page. ClientScript. GetCallbackEventReference (this, "arg", "GetRegister", "context ");
// Create the ServerSum method. When the client calls the method, it calls back the GetRegister method, passes the parameter to RaiseCallbackEvent (string eventArgument), and finally passes
// The GetCallbackResult () method sends the returned value to the client.
String RegisterFun = string. Format ("function ServerSum (arg, context) {{{ 0 }}}", CallBackFun );
Page. ClientScript. RegisterClientScriptBlock (this. GetType (), "ServerSum", RegisterFun, true );
}
String mssage = string. Empty;
# Region ICallbackEventHandler Member
Public string GetCallbackResult ()
{
Return "server: Hello, your username is:" + u. Name + "your Age is" + u. Age;
}
Public void RaiseCallbackEvent (string eventArgument)
{
JavaScriptSerializer js = new JavaScriptSerializer ();
U = js. Deserialize <Users> (eventArgument );
}
# Endregion
}
Users class
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
/// <Summary>
/// User Summary
/// </Summary>
Public class Users
{
String name;
Public string Name
{
Get {return name ;}
Set {name = value ;}
}
String age;
Public string Age
{
Get {return age ;}
Set {age = value ;}
}
}
Principle:
The server uses JSON to send an object to the server. after implementing the ICallbackEventHandler interface, the server overwrites the GetCallbackResult and RaiseCallbackEvent methods. During callback
Deserializing JSON in and returning the result to the client in GetCallbackResult. I will try again later. Thank you for your discussion!