Mar 20

Overview

This example will explain how to use the Prototype.js Javascript library to perform a simple Ajax call from an html page to an ASP.NET page with dynamic info. In this example the dynamic ASP.NET page is getting the current date and time, in a real-world example an ASP.NET page could parse RSS feeds, show stocks quotes, lookup weather, etc.

Requirements

Let’s code!

  1. Create a web form called ShowTime.aspx (ShowTime.cs will be auto created) in Visual Studio 2005 and add a label control as shown below:
    <asp:label id="lblDateTime" runat="server" />
  2. Open up ShowTime.cs and declare a DateTime type variable and set it to display the current date and time:
    DateTime dtRightNow = DateTime.Now;
  3. Inside the Page_Load set the page to not cache itself with the following code:
    Response.CacheControl = "no-cache";
  4. Assign the current date and time to the lblDateTime control:
    this.lblDateTime.Text = String.Format("{0:d}", dtRightNow) + " @ " + String.Format("{0:T}", dtRightNow);
  5. Now let’s create ShowTime.html. This page will call the Prototype.js and contain some Javascript to make an Ajax call to ShowTime.aspx
  6. Between the <head></head> tags, reference the Prototype.js Javascript library like this: <script type="text/javascript" src="js/prototype.js" />.
  7. Now we will write the Javascript that uses Ajax.Updater from Prototype.js. Below is the code that declares the page containing the dynamic content and the element to output the data when the link is clicked (you could also include the snippet below in a seperate Javascript file).
    <script type="text/javascript">
            function clickShowTime() {
                var url = "ShowTime.aspx";
                var display = "output";
                
                $('showtimelink').onclick = function() { 
                    return ajax(url, display); 
                    };
                }
            
            function ajax(url, display) {
                new Ajax.Updater(display, url, {asynchronous:true, evalScripts:true});
                return false;
                }
                
            window.onload = function() {
                clickShowTime();
                };
        </script>
  8. We’re almost done! Just need to ad add a few more things between the <body></body> tags. We will add a link with an ID called showtimelink and a <div> with the ID of output.
    <div><a href="#" id="showtimelink">Click this link to show current date & time</a></div>;
    <div id="output"></div>;
    
  9. That’s it! View the demo.

Download