Posts tagged Ajax

Working with ASP.NET Async Events

0

If you have ever worked on a project involving ASP.NET Ajax or used the ScriptManager or UpdatePanel control, then you would know what are ASP.NET Ajax events. If you dont, fret no, by the time you are done reading this article you will know.

What is ASP.NET Ajax?

ASP.NET AJAX is a set of extensions to ASP.NET developed by Microsoft for implementing Ajax functionality. Which brings us to “What is Ajax?”

Ajax (shorthand for asynchronous JavaScript and XML) is a methodology of new age web development ( heard of Web 2.0?… yeah you are on the right track ).

Did you notice my triple emphasis on the word methodology? There I did it again 😀 Well thats the main point to be understood. Ajax is a method or a technology. You can use Ajax in any of the programming or scripting languages out there. Asp, php even plain html will do.

With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax has led to an increase in interactive or dynamic interfaces on web pages and better quality of Web services due to the asynchronous mode. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of JavaScript and XML is not actually required, nor do the requests need to be asynchronous.

To make it simple, head over and try out these steps:

  • In Gmail, switch from inbox to draft. Part of the page is changed, but the page is not refreshed. You remain on the same page. Url has not changed (except for the #draft at the end of the url, but that’s still the same webpage).
  • In Google Reader, select a feed. The content changes, but you are not redirected to another url.
  • In Google Maps, zoom in or zoom out. The map has changed, but you remain on the same page.

What was different on those webpages from the other similar pages? The content of the webpage changes or updates without refreshing or redirection. Thats is what is Ajax is used for. It allows you to asynchronously (in the background) query a server and update the webpage content.

ASP.NET and Ajax

The term Ajax was coined back in 2005 and approved by W3C in 2006. Ajax was made available to various programming languages but it was difficult to implement since there was no standard and different people used to implement it differently. Also on a page with lots of controls, it was a lot of hard work to manage between updating and non-updating controls.

Microsoft worked upon this and made available some tools with the release Ajax Extensions and it was synchronized with the availability of .NET Framework 3.5

Microsoft made available some controls such as ScriptManager and UpdatePanel which turned out to be a boon (sometimes a pain-in-the-a**) for ASP.NET Developers. These controls allowed a developer to wrap Ajax functionality over a variety (almost all) the controls very easily.

Learn more about ASP.NET Ajax here. It has lots of tutorials, samples to get you started with ASP.NET Ajax.

ASP.NET Async Events

Many a times, when you use the UpdatePanel control, you would require to do some notifications of some sorts. The UpdatePanel by default fires up whenever any button is clicked which are contained by it. But what it doesnt do is, it doesnt notify the user about anything. It simply goes about, queries the server, gets the response and updates the content of the webpage and the user might not even notice it. You might want to alert the user when the process is complete, or there was an error while querying the server, or you might want to show a “processing…” message or a notification of some sorts. In that case, ASP.NET Ajax has made available four different events which you can handle to provide a proper notification.

Following table shows details of Events,

Event Name Description
beginRequest Event Raised before processing of an asynchronous postback starts and the postback request is sent to the server.
endRequest Event Raised after an asynchronous postback is finished and control has been returned to the browser.
initializeRequest Event Raised during the initialization of the asynchronous postback.
pageLoaded Event Raised after all content on the page is refreshed as the result of either a synchronous or an asynchronous postback.
pageLoading Event Raised after the response from the server to an asynchronous postback is received but before any content on the page is updated.

Uses

  • beginRequest: can be used to call custom script to set a request header or to start an animation that notifies the user that the postback is being processed.
  • endRequest: can be used to provide a notification to users or to log errors.
  • initializeRequest: can be used to cancel a postback.
  • pageLoaded/ pageLoading: can be used to provide a custom transition effect for updated content.

Steps to follow:

Follow these steps to handle the events listed above. They are handled on the client-side using JavaScript.

To notify the ASP.NET process that you want to handle the events, you need to register for them using the following syntax:

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler)

where beginRequestHandler is the name of the function to call when the event occurs. Similary you can also use…

add_initializeRequest(InitializeRequest);
add_endRequest(EndRequest);
add_pageLoaded(pageLoaded);

Simple write the JavaScript code which you want to be executed in the function and the rest will take care of itself.

Example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
//Lets set the time when the page is invoked.
protected void Page_Load(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString();
}
//When the button is clicked, we update the time on the label
protected void Button1_Click(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Working with Ajax Events - Test page</title>
<script language="javascript" type="text/javascript">
//this method will be called when the html part is loaded.
//it simply registers a method with one of the ajax events.
//for now we are registering for the end request which
//will be called when the ajax request is fully complete
function OnAjaxComplete()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)
}
//this method will be invoked when the ajax request is complete
//do anything you want in this block
//for now we just display a message
function endRequestHandler(sender, args)
{
//check if any error or exceptions occured and show the appropriate message
if (args.get_error() == null)
{
alert("Ajax update completed successful");
}
else
{
alert("An error occured while updating");
}
}

</script>
</head>
<body onload="OnAjaxComplete();">
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="UP1">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

It certainly helps in notifying the user about the process complete as ajax updates or mostly not “so visible” to user. Also you can handle the other events to show loading or processing animations. Give it a try. 🙂

Show message on UpdatePanel update

0

Several times, we are in a situation where we need to do some work the moment the update panel finishes its update (ASP.NET 2.0 AJAX). There are situations like showing an error if any during the update, showing a success message after a proper update, setting up scroll bars, changing some UI component, updating some other part of UI, etc. The list can get longer as per the developer’s requirement. I had tried to show how we can get control to the page once the update is finished. We can tweak things via JavaScript the way we need to out there in the handler.

Earlier I too faced lots of problem and was unable to work out of how to handle anything JUST after an update of update panel. I found lots of my colleagues facing the same issue. They wanted to have a certain UI work like scroll or to trap an error after the update. Googling didnt give me any success either. It was a real difficult time for my friends to find out the way to handle it.

It is said “Big things come in small packages” and thats what has happened here. You will understand when you read the solution below.

The thing that we are going to use is “adding an end-request handler to the request-manager”.

We add the handler to the request manager during page load via JavaScript.

function OnSubmitSuccess()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SubmitSuccessHandler);
}

Now, after having this piece of code in place, whenever the update panel finishes its update, the request would go through the SubmitSuccessHandler.

SubmitSuccessHandler needs to be placed now. In the handler, one can write whatever requirement one asks for. Errors can be trapped, scrolls can be set, any UI component can be updated.

function SubmitSuccessHandler(sender, eArgs)
{
/* This function can be used to do anything you want to be done after the update of Update Panel. You can run any JavaScript code you want to run from here. */
if (eArgs.get_error() == null)
{
alert("Update was successful");
}
else
{
// There was an error in the update panels update
// caught here and message displayed via JavaScript
alert("There was an error in update:"+eArgs.get_error().message);
}
}

Ajax CalendarExtender – Date Validation

0

I’ve just been asked to find a solution to stop users choosing dates in the past in a calendarextender control.  After using a little google-phoo, I found a couple of solutions which involved extending the extender itself.  Altering the calendar.js then recompiling it and putting it back into your solution.  That just seems a bit excessive to me.  So I got to thinking couldn’t I just use some in page JavaScript to trap the date entered. The Solution was pretty simple:

First we add a text box and a calendarextender:


 

you may notice that the CalendarExtender has an event attached (checkDate) – this is the JavaScript function you want it to call when ever you select a new date, add this function the top of your aspx page:

     

Simple and the nice thing is it’s reusable for all the calendarextenders on your page, just add the checkDate function to your other extenders.

AJAX is so much fun!!

0

As you all remember, I am now working for a software company called Tecogis. Read here (>).

Well I have been assigned to team developing a website in ASP.NET using VB.NET and AJAX features. Frankly speaking, a day ago, I didnt knew VB.NET at all. Never touched, felt, viewed, tried, read etc. And in around 2 hours, I am coding in VB.NET 😀

Its easy !!

Using AJAX is another fun. UpdatePanel makes your life so much easier 🙂 Hats of the development team at Microsoft or whoever made this control.

Off to coding, Boss is around 😀

Ciao.

.NET 3.5 Enhancements Training Kit

0

Microsoft has recently released an updated training kit with presentations, hands-on labs, demos and event materials describing features found in .NET 3.5 SP1 and Visual Studio 2008 SP1. Here you will find over 100 MB of information with tips on using MVC, Ajax, the Entity Framework, Visual Studio 2008 SP1 and other tools. Materials used world wide in the .NET 3.5 SP1 training tour are also included. You can read more details here. In the download section shown below, I also include a link to the VS 2008 training kit released last Fall.

Downloads

Go to Top