Microsoft Study Bible

November 27, 2009

How to achieve Ajax in Asp.net 2.0?

 
ASP.NET 2.0 Client side Callbacks Framework
ASP.NET 2.0 has been released for a long time .The 2.0 framework has a great number of new features, one of which is Client side Callback. It can retrieve page values and populate them to an already-generated page with out reconstructing page. This makes it possible to use on a page with out going through the entire post back cycle; that means you can update your pages without completely redrawing the page. Client side Callback allows us to call the server-side methods without postback, which is consistent with the features of AJAX. However, AJAX can custom the method called that Callback of .NET 2.0 can not .The prerequisite to use Client Side Callback is to achieve System.Web.UI.IcallbackEventHandler interfaces, which contain two methods.
//call this method when the client callback
public void RaiseCallbackEvent(String eventArgument)
//After implementation of RaiseCallbackEvent , Call this method whose return value

// is sent back to the client side. 
  public string GetCallbackResult()

  
for example:
  .cs:
  String cbReference = Page.ClientScript.GetCallbackEventReference(
  this,”arg”, “ReceiveServerData”, “context”);
  String callbackScript;
  callbackScript = “function CallServer(arg, context)” + “{ ” + cbReference + “} ;”;
  Page.ClientScript.RegisterClientScriptBlock(
  this.GetType(),”CallServer”, callbackScript, true);
  javascript:

AJAX Introduction

AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications. With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly.
AJAX mechanism
When we used XmlHttp to achieve no-fresh page, we used XmlHttp to request a hidden page and Asp/Asp.Net of HttpHandler’own. Although in Ajax, we also request a hidden page ,the difference of the page of HttpHandler is achieved by ourselves.
Build your own AJAX:
1. Firstly we need to achieve a HttpHandler to respond the client’s request:
If we want to achieve self-define HttpHandler we should achieve IHttpHandler interfaces ,which contain a property and a method :
bool IHttpHandler.IsReusable
  void IHttpHandler.ProcessRequest(HttpContext context)
  Example:
  bool IHttpHandler.IsReusable
  {
  get { return true; }
  }
  void IHttpHandler.ProcessRequest(HttpContext context)
  {
  context.Response.Clear(); // To obtain the method called
  string methodName = context.Request.QueryString["me"];
  //To obtain the assembly information
  //Czhenq.AJAX.Class1.Dencode is self-defining string coding
string AssemblyName = Czhenq.AJAX.Class1.Dencode(context.Request.QueryString["as"]);
  //acquire the parameters of the method
  string Arguments = context.Request.QueryString["ar"]; //start to call the method
  Type type = Type.GetType(AssemblyName);
  MethodInfo method = type.GetMethod(methodName,
  BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
  if (method != null)
  {
  //The parameters are separated by “,”
  string[] args = Arguments.Split(”,”.ToCharArray());
  ParameterInfo[] paras = method.GetParameters();
  object[] argument = new object[paras.Length];
  for (int i = 0; i < argument.Length; i++)
  {
  if (i < args.Length) {
  //As the parameters passed from XmlHttp are all string type, all of them are must converted .
//Here just convert the parameters into Int32
  argument[i] = Convert.ToInt32(args[i]);
  }
  }
  object value = method.Invoke(Activator.CreateInstance(type, true), argument);
  if (value != null) context.Response.Write(value.ToString());
  else context.Response.Write(”error”);
  }
  //end of process
  context.Response.End();

2. Client side Javascript code:
function CallMethod(AssemblyName,MethodName,Argus)
  {
  var args = “”;
  for(var i=0;i)
  args += Argus[i] + “,”;
  if(args.length>0) args = args.substr(0,args.length-1);
  var xmlhttp = new ActiveXObject(’Microsoft.XMLHTTP’);
  url = “AJAX/AJAX.czhenq?as=” + AssemblyName + “&me=” + MethodName +”&ar=”+ args;
  xmlhttp.open(”POST”,url,false);
  xmlhttp.send();
  alert(xmlhttp.responseText);
  }

3.We have achieved a simple AJAX framework. Now we need to write a piece of code to test it.
Use your own AJAX
1. New a website, and use your written HttpHandler, and register your HttpHandler on Web.config to explain that those requests will use your written Handler. The following description is all of request ending up with “czq” will use “Czhenq.HttpHandlerFactory” to deal with them.
</type=”Czhenq.HttpHandlerFactory, Czhenq.AJAX”/>

2. Add a web page and copy the script to the page and add a method you want to call .
private string Add(int i, int j)
  { return TextBox1.Text;  }
3. Place a HieddenField control on the page which is named AssemblyName.And add the following code in the Page_Load.
string assemblyName = Czhenq.AJAX.Class1.Encode(
  typeof(_Default).AssemblyQualifiedName);
  AssemblyName.Value = assemblyName;

4. Add the following script on the page
 var assemblyName = document.getElementById(”AssemblyName”);
  var argus = new Array();
  argus.push(”100″);
  argus.push(”200″);
  CallMethod(assemblyName,”Add”,argus)

Summarization
AJAX is not a new technology, which is just combination of some technology existed. In my opinion, AJAX is to encapsulate XmlHttp called by JavaScript, which just change the ways to write the code.

Encode and Decode:
public static string Encode(string value)
  {
  byte[] bytes = ASCIIEncoding.ASCII.GetBytes(value);
  return Convert.ToBase64String(bytes);
  }
  public static string Dencode(string value)
  {
  byte[] bytes = Convert.FromBase64String(value);
  return ASCIIEncoding.ASCII.GetString(bytes);
  }

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress

Close
E-mail It