Oct 26 2006

JQuery and ASP.NET - lets involve ASP.NET

Posted by admin under Ajax

In this example we create a table - and a span

When clicked on the span an Ajax request shold be made - from the serverside the current minute should be returned - and the the current minute is label should be updated:

Really easy and it's pretty much like the first Ajax example here at ASPCode.net - Starting with Ajax.NET - meaning we (as opposed to the case with Ajax.NET ) need to create a specific handler (ASHX) to handle the ajax request on the server.

Lets start there - at the serverside:

ajaxdata.ashx



<%@ WebHandler Language="C#" Class="ajaxdata" %>

using System;
using System.Web;

public class ajaxdata : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
        context.Response.ContentType = "text/plain";
        context.Response.Write( TimeServer.Minute() );
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


We just returns a simple text returned from TimeServer.Minute() - which just returns  DateTime.Now.Minute() - but after a         System.Threading.Thread.Sleep(2000); - simulating a long operation.

Anyway, we have been into that before - lets look how the client side looks when using JQuery:



<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
	$('#clickmeupdate').click(function() {
		MyUpdate();
	});
});


   
function MyUpdate()
{
 $.get("ajaxdata.ashx",function(xml){
   $('#lblMinute').html(xml);
  });
 }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <span style="background-color:LightBlue" id="clickmeupdate" >Click me to update</span>
    <table border="1">
    <tr>
    <td>Something</td>
    <td><asp:Label ID="lblDataUpdated" runat="server">Hello there bla bla</asp:Label></td>
    </tr>
    <tr>
    <td>Other important stuff</td>
    <td>Again more bla bla</td>
    </tr>
    <tr>
    <td>Current minute is</td>
    <td><asp:Label ID="lblMinute" runat="server"></asp:Label></td>
    </tr>
...
...
...

As you can see the code looks pretty slick. I really like it! the $.get function initiates the call - and we also specify a funciton object (the callback) as one of the parameters to it. And in the callback we just set the result using the html() function on the $('#lblMinute') object.

I will work more on this - next step is adding a "Loading" animation - and later in this article serie I will try to acchieve a more generic data handling scheme by using JSON.

 

Attachments