Four Ways to Locally Update a Web Page
 
Published: 05 Sep 2007
Abstract
This article examines the different ways to update a web page locally.
by Xianzhong Zhu
Feedback
Average Rating: 
Views (Total / Last 10 Days): 56053/ 183

Introduction

These days in developing Web 2.0 applications, how to locally update a web page becomes one of the most crucial and interesting topics. In this article from the point of view of an ASP.NET 2.0 developer, I will show you four different ways to achieve this goal with concrete examples.

In fact, there have already been several techniques coming into the locally updating stage before the term "AJAX" was coined.  Now let us first start researching into the IFrame approach.

The IFrame Way

Iframe, which has been part of the HTML specification since version 4 and is supported in nearly all modern browsers, is the webpage element that creates an inline frame that contains another document. Iframe functions as a sub document within a document, or like a floating frame.  It is able to load another html document within the <iframe> tags.

The following example uses the IFRAME element and an HTML fragment to create a frame containing the main page of google.

Listing 1: An example of a minimal IFRAME

<IFRAME ID=IFrame1 FRAMEBORDER=0 SCROLLING=NO SRC="http://www.google.com">
</IFRAME>

Grammatically, the usage of IFRAME quite simulates that of div, such as you can specify the position, color and layout of them embedded inside a web page. The following table gives the commonly-used parameters for an IFrame element.

Table 1: Parameters for an HTML Iframe Element

Parameters

Comments

Src

URI (URI of frame content)

Name

CDATA (name of frame)

Longdesc

URI (link to long description)

Width

Length (frame width)

Height

Length (frame height)

Align

[ top | middle | bottom | left | right ] (frame alignment)

Frameborder

[ 1 | 0 ] (frame border)

Marginwidth

Pixels (margin width)

Marginheight

Pixels (margin height)

Scrolling

[ yes | no | auto ] (ability to scroll)

Enough already with the concept!  Let us get to the code.

Sample 1

1. Launch Visual Studio 2005 and then select menu item "File | New Website…" to create an ASP.NET website named IFrameWay (select Visual C# as the built-in language).

2. Open the web page "Default.aspx," switch to the design view, and add controls as seen in the following figure.

Figure 1: The design-time snapshot for Sample 1

As shown from the above figure, this is a basic sample.  When the users input the name of a city and click "Search," the searched results will be listed inside a DropDownList control just below button "Search."  This process must be asynchronous and the updating should be limited to the specified area (i.e. within the DropDownList control area).

3. With the aim in mind, let us start the coding. Switch to the source code view of page "Default.aspx" and embed an iframe element within the lower right corner of the above table.

Listing 2

<iframe src="subpage.aspx" style="TEXT-ALIGN: center" id="iframe1" 
    width="100%" height="100%" frameborder="0" scrolling="auto"/>

Note, here we embed another small webpage within the iframe element.

4. When the user clicks the button "Search," we need to pass the name of the city he has just entered to the embedded page of the above iframe element. The following corresponds to the click event handler of button "Search."

Listing 3

function Search()
{
  var city=document.getElementById("txtCity").value;
  if(city !="")
    {
      document.getElementById("iframe1").src=" subpage.aspx?city=" +city;
    }
}

5. Right click the project, add a new ASP.NET page and name it "subpage.aspx."  In this article this page acts as a broker to transfer data between the client side and the server side.

6. Drag a DropDownList control onto the page and press F7 to switch to the CodeFile "subpage.aspx.cs."  Here is the merely method to be programmed with it.

Listing 4

protected void Page_Load(object sender, EventArgs e)
{
  string city = Request.QueryString["city"];
  switch (city)
  {
    case "BeiJing":
      DropDownList1.Items.Clear();
      DropDownList1.Items.Add("Chao Yang");
      DropDownList1.Items.Add("Hai Dian");
      DropDownList1.Items.Add("East City");
      DropDownList1.Items.Add("West City");
      break;
    case "ShangHai":
      DropDownList1.Items.Clear();
      DropDownList1.Items.Add("Pu Dong");
      DropDownList1.Items.Add("Jing An");
      DropDownList1.Items.Add("Hong Kou");
      DropDownList1.Items.Add("Xu Hui");
      break;
    case "WeiFang":
      DropDownList1.Items.Clear();
      DropDownList1.Items.Add("Fang Zi");
      DropDownList1.Items.Add("Wei Cheng");
      DropDownList1.Items.Add("Kui Wen");
      DropDownList1.Items.Add("Kai Fa");
      break;
  }
}

Here, just for demonstration, we have hard coded the data. We obtain the passed city from the main page using Request object, and then populate the control DropDownList1 with the related area data.

That is it - all the things are done on the server side.

7. Now, right click page "Default.aspx," set it as the startup page and click "Preview in the browser."  Without anything wrong, you will get the run-time snapshot like Figure 2.

Figure 2: The run-time snapshot for Sample 1

When the user inputs the name of his favorite city and clicks the button "Search," the following DropDownList control will be populated with the associated area data. Of course, the clicking action only results in the local updating (i.e. filling in the DropDownList control).

Author's Notes:  1. Today, there are tons of debates on the Internet on IFrame - good or bad.  The very "bad" may mainly dwell on search engine optimizations; there is, however, a great  article which gives a better idea of utilizing IFrame.  2. Please be sure to differentiate IFrame (i.e. inline frame) from frame.  An inline frame is just a frame within a single page usually containing another page - it can exist without having a frameset defined, while a frame is part of the browser display but exists as part of a frameset.

Next, let us examine the second commonly used approach to partially update a web page - JavaScript.

The JavaScript Way

As early as ASP.NET 1.0, several means, such as Page.RegisterClientScriptBlock and Page.RegisterStartupScript, were created to boost up the server controls with the capacities of client side. In the current ASP.NET 2.0, the above two methods both became obsolete and were replaced by class ClientScriptManager which can be accessed using Page.ClientScript.  One of the important methods of Page.ClientScript is RegisterClientScriptBlock through which we can achieve the goal of injecting client-side JavaScript blocks into object Page. Therefore, we can succeed in populating the required data from the server side, and thus ensure to locally update a web page.

About Method RegisterClientScriptBlock

There are two signatures for this method, as illustrated in the following Listing.

Listing 5

ClientScriptManager.RegisterClientScriptBlock (Type type, String key, 
    String script);
ClientScriptManager.RegisterClientScriptBlock (Type type, String key, 
    String script, Boolean addScriptTags);

A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page. Attempting to register a script that is already registered does not create a duplicate of the script.

Call the IsClientScriptBlockRegistered method to determine whether a client script with a given key and type pair is already registered and avoid unnecessarily attempting to add the script.

In this overload of the RegisterClientScriptBlock method, you must make sure that the script provided in the script parameter is wrapped in a <script> element block.

The RegisterClientScriptBlock method adds a script block to the top of the rendered page. The script blocks are not guaranteed to be output in the order they are registered. If the order of the script blocks is important, use a StringBuilder object to gather the scripts together in a single string, and then register them all in a single client script block.

In this article we are not going to dig further into the related theory behind but concentrate on constructing an associated example to show the usage of method Page.ClientScript.RegisterClientScriptBlock.

Author's Note: In ASP.NET AJAX there is also a method RegisterClientScriptBlock which is provided by ASP.NET Server controlScriptManager. We can use it to create the Server side Extender for ASP.NET AJAX.

Sample 2

1. Create a Sample Web Site

Launch Visual Studio 2005 and create an ASP.NET website named JavaScriptWay (select Visual C# as the built-in language).

Open the web page "Default.aspx" and make some modification with it. The following Figure gives the final design-time snapshot.

Figure 3: The design-time snapshot for Sample 2

Note that here the DropDownList control is directly embedded inside the page, in contrast to that in Sample 1.

Now, let us start to research into the most interesting part - injecting JavaScript into the client side.

2. Inject the client-side JavaScript

Press F7 and switch to the CodeFile "Default.aspx.cs."  With the foregoing analysis, we would better achieve the goal of injecting all the required JavaScript functions into the client side at the very time the page just start being loaded. OK, the best site should be function Page_Load. Listing 6 shows the interesting inner workings.

Listing 6

protected void Page_Load(object sender, EventArgs e)
{
  StringBuilder myscript = new StringBuilder();
  myscript.Append("function Search()    {\n");
  myscript.Append("var city=document.getElementById('txtCity').value; \n");
  myscript.Append("switch(city)       {\n");
  myscript.Append("case 'BeiJing': \n");
  myscript.Append("FillData('" + GetAreaStr("BeiJing"+ "'); \n");
  myscript.Append("break; \n");
  myscript.Append("case 'ShangHai': \n");
  myscript.Append("FillData('" + GetAreaStr("ShangHai"+ "'); \n");
  myscript.Append("break; \n");
  myscript.Append("case 'WeiFang': \n");
  myscript.Append("FillData('" + GetAreaStr("WeiFang"+ "'); \n");
  myscript.Append("break; }\n");
  myscript.Append(" }\n");
  if (!Page.ClientScript.IsClientScriptBlockRegistered("Search"))
  {
    Page.ClientScript.RegisterClientScriptBlock(typeof(string), "Search",
      myscript.ToString(), true);
  }
}
 
private string GetAreaStr(string city)
{
  string area = "";
  switch (city)
  {
    case "BeiJing":
      area = "Chao Yang,Hai Dian,East City,West City";
      break;
    case "ShangHai":
      area = "Pu Dong,Jing An,Hong Kou,Xu Hui";
      break;
    case "WeiFang":
      area = "Fang Zi,Wei Cheng,Kui Wen,Kai Fa";
      break;
  }
  return area;
}

Here, we have created and embedded a JavaScript function "Search" into a StringBuilder object; finally, we call Page.ClientScript.RegisterClientScriptBlock to inject the code of JavaScript function "Search" into the client side. In building up the string we have mentioned a client-side helper function "FillData" which must be created on the client side.  Also, for simplicity, we have hard coded the helper function GetAreaStr.

For now, cute readers may have noticed something. Undoubtedly, we have hard coded the JavaScript code to be injected into the client side, which obviously results in poor flexibility.

3. The client-side Coding

Now, let us take a quick look at the client-side function FillData. The following lists the complete source code of this function.

Listing 7

function FillData(strArea)
{
  document.getElementById("DropDownList1").options.length = 0;
  var indexofcity;
  var city;
  while (strArea.length > 0)
  {
    indexofcity = strArea.indexOf(",");
    if (indexofcity > 0)
    {
      city = strArea.substring(0, indexofcity);
      strArea = strArea.substring(indexofcity + 1);
      document.getElementById("DropDownList1").add(new Option(city, city));
    }
    else
    {
      document.getElementById("DropDownList1").add(new Option(strArea, strArea))
        ;
      break;
    }
  };
}

Simply put, this function uses a while loop to cut the passed string (which holds area names related to the city specified by the user) into pieces and populate the control "DropDownList1" with them.

That is all!  Now it is time to appreciate the final result. Just press F5 and, without anything wrong, you will see the run-time snapshot as displayed in Figure 4.

Figure 4: The run-time snapshot for Sample 2

Next, let us continue to dig into another way to achieve the partially updating effects.

Callback in ASP.NET 2.0

One of the most attractive features that ASP.NET 2.0 has contributed to the web development field is the script callback, which allows you to make a server-side call from the client side without posting back to the server. In essence, the client-side script callback utilizes the XmlHttp component implemented by most of the up-to-date web browsers to set up communication with the server side. The following Figure describes the rough mechanism of the client-side script callback inside ASP.NET 2.0 architecture.

Figure 5: Mechanism of the ASP.NET 2.0 client-side script callback

As depicted by the above figure, performing a client callback involves the following steps:

1. Call the page's GetCallbackEventReference method to get the name of a client-side function that will be called to initiate a callback. (Note that the GetCallbackEventReference method is declared in the ICallbackEventHandler namespace, and thus your server-side controls must explicitly implement that interface ; and accordingly, your client-side JavaScript has to explicitly call ClientScript.GetCallbackEventReference() method.)  Then, that function is called from the client side.

2. That function prompts ASP.NET's callback manager, which is itself implemented in client-side script, to launch an XMLHTTP callback to the server.

3. On the server side, ASP.NET receives the call and invokes the page's ICallbackEventHandler.RaiseCallbackEvent() method, which processes and returns the callback.

4. The callback manager is notified that the execution has completed.

5. The callback manager notifies the caller that the call was completed by calling a client-side notification function (provided by the caller when it initiated the call).

In the next section, we are to create a sample to demonstrate ASP.NET 2.0's script callback feature, by which we are also to achieve in partially updating a web page.

Sample 3

1. Create a Sample Web Site

To start, launch Visual Studio 2005 and create a new ASP.NET 2.0 web site project. Name the project CallbackRefresh (select Visual C# as the built-in language).  Populate the default Web Form (Default.aspx) with the controls as shown in Figure 6.

Figure 6: The design-time snapshot of page Default.aspx in web site CallbackRefresh

In the above Figure we add a TextBox control to let the user enter the category of his/her favorite animal, a Button "Search" for the user to inquire (asynchronously from the server side) all the animals that belong to his/her selected category, and a DropDownList control to hold and show all the animals associated with the selected category.

Now, let us first figure out the client-side solution.

2. Client-side Programming

Herein we are mainly interested in the click event handler associated with the above HTML input element "btnSearch," whose source code is listed as follows:

Listing 8

function FillData()
{
  var ani=document.getElementById("txtCategory").value;
<%=this.ClientScript.GetCallbackEventReference(this,"ani","FillDropDownList",null)  %>;
}

It is pretty short. In the first sentence, we get the category name that the user has just entered while the true secrecy lies in the second sentence.

Here, we use the ASP.NET <%...> block to embed a code block in this web page (this means it is primarily to preserve backward compatibility with older ASP technology due to its easily resulting in complex programming logic. However, we use it here just for demonstration.).  In fact, an embedded code block is a piece of server-side code that executes during the page's render phase. The code in the block can execute programming statements and call functions in the current page class. So, the above sentence is equal to calling function Page.ClientScript.GetCallbackEventReference within the code-behind page. This function is responsible for implementing the callback on the client side. We have to use this method to generate client-side code, which is a must have to instantiate the asynchronous call to the server.

When you execute this page from the browser and view the HTML source code, you will see that it generates the following callback code due to the above GetCallbackEventReference method call:

Listing 9

WebForm_DoCallback('__Page',ani,FillDropDownList,null,null,false);

WebForm_DoCallback is a JavaScript function that in turn invokes the XmlHttp class methods to actually perform the callback (you can refer to this article to further dig into WebForm_DoCallback).

In a nutshell, the above method GetCallbackEventReference combines the client-side function FillDropDownList with the two server-side methods - GetCallbackResult and RaiseCallbackEvent (both declared inside interface ICallbackEventHandler) remotely to achieve the client-side callback mechanism.

Now, let us turn our attention to the true client-side callback function.

Listing 10

function FillDropDownList(sAnimal)
{
  document.getElementById("DropDownList1").options.length = 0;
  var index;
  var ani;
  while (sAnimal.length > 0)
  {
    index = sAnimal.indexOf(",");
    if (index > 0)
    {
      ani = sAnimal.substring(0, index);
      sAnimal = sAnimal.substring(index + 1);
      document.getElementById("DropDownList1").add(new Option(city, city));
    }
    else
    {
      document.getElementById("DropDownList1").add(new Option(sAnimal, sAnimal))
        ;
      break;
    }
  };
}

As is easily seen here, we populate the "DropDownList1" with data asynchronously returned from the server.

Now, continue with the server-side programming.

3. Server-side Programming

As introduced in the previous sections, we must let the server control (here it refers to the web page itself) implement interface ICallbackEventHandler. The following is the related code:

Listing 11

public partial class _Default: System.Web.UI.Page, ICallbackEventHandler
{
  private string _data;
  //……(omitted)
  public string GetCallbackResult()
  {
    return _data;
  }
  public void RaiseCallbackEvent(string eventArgument)
  {
    switch (eventArgument)
    {
      case "Cat":
        _data = "Felix,John,Mary,Rossy";
        break;
      case "Dog":
        _data = "Fido,Rover,Kissy";
        break;
      case "Cow":
        _data = "Daisy,Mighty,Hassy,Hover";
        break;
      case "Parrot":
        _data = "Polly,Curo,Paul,Pazz";
        break;
    }
  }
}

Here, method RaiseCallbackEvent of interface ICallbackEventHandler is responsible for setting up values according to the passed parameter, while method GetCallbackResult merely returns the data processed by the previous method. The two methods, you see, have cooperatively accomplished the server-side task associated with the client-side callback operation.

For now, you can press F5 to start the application. Input your favorite animal category, click on the "Search" button and you will noticed the DropDownList control below is filled with animals that belong to the specified category. And also, the filling process takes place asynchronously.

Figure 7: The run-time snapshot for the callback way

The Ajax Way

The best benefits AJAX brought to people should be the asynchronous calling and partially refreshing. In contrast to the above techniques, the AJAX way is generally considered as the simplest approach to achieve the locally updating result. Since there are abundant preliminary materials concerning AJAX, we do not give unnecessary details about it any more, but go straight to the related sample.

Sample 4

Before going on, let me give you a rough sketch of the mechanism for the following sample to achieve the locally updating effect.

Figure 8: The mechanism of the AJAX way to locally update a web page

Now, let us start to build the AJAX style example.

1. Create a Sample Web Site

1. Launch Visual Studio 2005, create a new ASP.NET website and name it "AjaxRefresh."

2. Open the default Web Form (default.aspx) and switch to the design-time view. Since nearly all the layout elements and user interface objects are similar with those in Sample 3, we select to omit giving the screen snapshot.

3. Press Shift+F7 to switch to the source code view of the page, and add click event handler for "Search."

Listing 12

<input id="btnSearch" style="width: 104px; height: 32px;" 
    type="button" value="Search" onclick="getData()" />

4. Create the XMLHttpRequest object, which is finished within function getData() (just the click event handler for "Search"). The following is part of the corresponding client-side JavaScript.

Listing 13

<script type="text/javascript">
var xmlhttp;
function createHTTP()
{
      //create different XMLHttpRequest objects according to different browsers
      if(window.ActiveXObject)
      {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      else if(window.XMLHttpRequest)
      {
            xmlhttp=new XMLHttpRequest();
      }
}
function getData()
{
      var sAnimal=document.getElementById("txt").value;
      createHTTP();
      xmlhttp.onreadystatechange=statechange;
      xmlhttp.Open("POST","datapage.aspx? sAnimal=" +sAnimal,true);
      xmlhttp.Send();
}
function statechange()
{
      if(xmlhttp.readystate==4)
      {
            if(xmlhttp.status==200)
            { 
                  FillData(xmlhttp.responseText);
            }
      }
}

In the above function getData(), we first get the name that the user has entered. Second, we create the asynchronous objectXMLHttpRequest by calling method createHTTP(). Third, we attach the state of object XMLHttpRequest to the client-side callback function statechange().  Then we load the web page to linkour aim is to asynchronously get the data supplied by page "datapage.aspx." Finally, we send out the request.

Within the callback function statechange(), when the asynchronous calling has finished and the status of object XMLHttpRequest becomes 200, we can safely start to fill the DropDownList control with the returned data, which is done by calling function FillData() (we are still not going to list the source code of this function since it is quite similar to that of above samples; for details you can refer to the downloadable source code at the end of the article).

2. Create a Sample Web Page as a Broker to Provide Data

As seen from above, we asynchronously invoke a web page named "datapage.aspx."  This page plays the role of a broker to provide data from the server side to the client side. Therefore, it is no use decorating the web page with controls; we only need to write necessary code within function Page_Load.

Listing 14

protected void Page_Load(object sender, EventArgs e)
{
  string sAnimal = Request.QueryString["sAnimal"];
  Response.Clear();
  switch (sAnimal)
  {
    case "Cat":
      Response.Write("Felix,John,Mary,Rossy");
      break;
    case "Dog":
      Response.Write("Fido,Rover,Kissy");
      break;
    case "Cow":
      Response.Write("Daisy,Mighty,Hassy,Hover");
      break;
    case "Parrot":
      Response.Write("Polly,Curo,Paul,Pazz");
      break;
  }
}

Here, we first obtain the passed parameter, and then return the related animals using method "Response.Write" according to the passed category entered on the client side. It is a really simple code snippet!

Author's Note: Using a server page as a broke to return processed data to the client side is the common means via initial AJAX programming under ASP.NET 2.0 environment.

That is it!  Now, you can press F5 to start the application to make the similar test as the above samples. You are suggested to pay more attention to the response speed in this AJAX way compared with all the other ways explained above. The following figure gives the run-time snapshot.

Figure 9: The run-time snapshot for the AJAX way

Comparison

OK, now it is time to make a rough comparison with the four solutions introduced in this article.

First, the four ways all succeed in partially updating a web page. However, if there are plenty of data to be processed, then the slowest one should be the IFrame solution. This is because IFrame belongs to the fully server side based solution. It interacts continuously with the server side, which causes serious influences on the response ability.

Second, the fastest approach should be that based on the JavaScript. This is because this solution fully relies on the client side without interacting with the server side again and again. However, it requires loading all the related data at the first time when the web page is loaded. Another drawback lies in that this solution needs quite a lot of JavaScript blocks, which may result in fattening the browser side.

The rather perfect and recommendable solution should be the AJAX way. With the XMLHttpRequest object being ready, to partially load data is pretty easy; and also, the relevant data can be selected under specified conditions all of which can be met either through XMLDOM or via regular expressions.

Third, it should be pointed out that the Callback way is generally suggested to be used to create custom server-side controls (and of course is widely applied in ASP.NET 2.0 server controls).

On the whole, with different applications, the four ways in this article can achieve different effects. Thus, what we should do is to try our best to grasp all of them and single out the one that most suits our concrete circumstances.

Downloads

Conclusion

In this article we have done some research into the commonly-used four ways to locally update a web page using four respective examples. These days, AJAX becomes one (accurately not the "one") of the most popular and valuable techniques to create web applications with quicker response and better user experience.

I have written this article only with the aim of summarizing traditional solutions in achieving a partially updating effect so as to better grasp the idea of AJAX. And, of course, the three foregoing ways have not become obsolete at all but own each respective scenario.



User Comments

Title: d   
Name: d
Date: 2012-10-24 12:04:07 PM
Comment:
d
Title: Locally update a web page   
Name: Santosh
Date: 2010-05-04 3:41:59 AM
Comment:
It's an amazing and really very very helpful article. After reading this article, I have become a fan of this site.... I request you to not delete this article, as it may be very helpful to many people.
Title: updating a web page   
Name: Mrs.
Date: 2009-05-19 3:23:22 PM
Comment:
this is great
Title: Download Links Does Not Work   
Name: Tarik
Date: 2008-11-07 9:04:04 AM
Comment:
Good Article , But Please Review The Downloads Links
Title: Mr.   
Name: Joydip Kanjilal
Date: 2008-10-16 10:25:58 AM
Comment:
Excellent!
Title: how up date webpage   
Name: MUHAMMAD YOUNUS TOOR
Date: 2008-09-08 10:32:32 PM
Comment:
I WANT LEARN ABOUT WEB PAGE MAKIN G






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-07-21 12:32:21 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search