C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » ASP.NET/Web Applications »

Save Changes on Close of Browser or when exiting the page.


Posted Date: 25 Sep 2007    Resource Type: Articles    Category: ASP.NET/Web Applications
Author: Abishek .R.SrikaanthMember Level: Bronze    
Rating: 1 out of 5Points: 10



Introduction



Many have been trying to implement the functionality of Saving the data on close of the browser. I was also one of you trying to find a way on how to implement the same. I had been to many forums and discussion boards, but couldn't find a way on how to implement this. I finally landed up at a particular piece of javascript code (attached below) to trap the close of IE window which actually helped me in completing this functionality.

Using the Code


Navigation in a site can happen in two ways. Following are the list of actions by which users can navigate.

(Navigating to pages using controls provided within the site.
Navigating to pages using Browser Controls, shortcut keys or the right click options. )

Following are the ways through which the user can navigate away from the page. All these are covered in this solution.

Navigation or postback using controls available in the application.

Image Buttons
Link Buttons
Submit Buttons
Server Controls with "Autopostback" option set to True

Navigation through user actions, browser buttons, shortcut keys, close of the browser. Following are a list of ways by which this is achieved.

Back button on the Browser Toolbar
Refresh button on the Browser Toolbar
Close button on the Browser Toolbar
Home button on the Browser Toolbar
ALT + F4 to close the browser
CTRL + F4 (for tabbed browsers)
F5 or CTRL + R or Right click for refresh
ALT + Home button (to navigate to client's Home page)
Click backspace (alternative for Back button)
Typing a URL and navigating to a different page
Selecting a URL from the favorites button
Right Click and select Refresh

Identifying the different actions and enabling save for each action is a tedious process. The save functionality can be implemented in a simpler way using the javascript event onbeforeunload.
Reason to use onbeforeunload:

The onbeforeunload event (which is called before unload event) is called when

* Navigating to another page (as mentioned above)
* Postback due to a control event
* Using controls on the Browser
* Closing the page.

Thus onbeforeunload is the appropriate event at which the save functionality can be implemented.
Implementation of the Save Functionality:

To differentiate between a user initiated event and a control initiated event an attribute is being added named tag with a value "DonotCallSaveonLoad" to all the known controls in the application using which the save method should be called without prompting the user to save the page.


LinkButton1.Attributes.Add("tag", "DonotCallSaveonLoad")
LinkButton1.Attributes.Add("onClick", "currentElement = event.srcElement;")
Button1.Attributes.Add("tag", "DonotCallSaveonLoad")
Button1.Attributes.Add("onClick", "currentElement = event.srcElement;")
ImageButton1.Attributes.Add("tag", "DonotCallSaveonLoad")
ImageButton1.Attributes.Add("onClick", "currentElement = event.srcElement;")
DropDownList2.Attributes.Add("tag", "DonotCallSaveonLoad")
DropDownList2.Attributes.Add("onClick", "currentElement = event.srcElement;")
myhref1.Attributes.Add("tag", "DonotCallSaveonLoad")
myhref2.Attributes.Add("tag", "DonotCallSaveonLoad")
myhref1.Attributes.Add("onClick", "currentElement = event.srcElement;")
myhref2.Attributes.Add("onClick", "currentElement = event.srcElement;")


The event.srcElement will set the object of the control to the variable currentElement which initiated the postback. This will be set on the onClick event of the control.

Note: onClick event is the only point where the Control object can be retrieved because the object of the control is destroyed when the process reaches the onbeforeUnload event.

The onbeforeUnload event calls the HandleOnClose function which checks if the variable currentElement has a value or not.


<body onbeforeunload="HandleOnClose(event)" >


The javascript function HandleOnClose checks for this attribute tag of the currentElement object. If the currentElement is null or the value of the attribute tag of the currentElement is not DonotCallSaveonLoad, then it calls the function FunctiontoCallSaveData, otherwise the save functionality on the code behind is called.


//Function called when the browser is closed.
function HandleOnClose(evt) {
if (currentElement == "" || (!(currentElement.getAttribute("tag")=="DonotCallSaveonLoad"))){
var objconfirm = confirm("Would you like to save changes made?")
if (objconfirm == true) {
FunctiontoCallSaveData();
}
}
}


The implementation of the function FunctiontoCallSaveData is the same as previously sent which is as follows.


//Function to submit the form and call the Page_load function on server side.
function FunctiontoCallSaveData()
{
document.getElementById("<%=hdtoSaveData.ClientID %>").value="PageClosed";
document.form1.submit();
}


The form.submit will in turn call Page_Load in which the Save functionality can be called. Error Handling can also be performed for this functionality. The same is shown in the code snippet below.


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not IsPostBack Then
LoadControls()
End If
If hdtoSaveData.Value = "PageClosed" Then
If drpError.SelectedValue = "Yes" Then
Dim a As Integer = 1
Dim b As Integer = 0
Dim x As Integer = CInt(a / b)
End If
SaveDataonPage()
End If
Catch ex As Exception
hdError.Value = ex.Message
ExceptionPolicy.HandleException(ex, "SamplePolicy")
GetDatafromTable("Error")
End Try
End Sub


Points to Note


This functionality cannot be debugged using Breakpoints. This functionality can be verified by the checking if the data has been updated in the datasource. In the attached demo, there is a SQL script which creates a temporary table to which data is stored on close of the browser. Please make necessary changes to the function SaveDataonPage on the .vb file as per your convinience. Exception Handling is implemented using Enterprise Library 2.0. Customizations can be done to it Exception Handling also.

Download Code from the following location: Save on Close Code Sample



Responses

Author: Vasudevan Deepak Kumar    27 Sep 2007Member Level: Diamond   Points : 0
Linking to another website just for the sake of binary download is a bad practice. I would say, you can link to your related article hosted with CodeProject.com. Furthermore, CodeProject restricts Zip Download for logged on members only and hence a direct binary link would only catch your visiters in a strange and beguile Logon Screen.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Save Changes  .  Exiting the page.  .  Close of Browser  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Jupload -- A review on elegant uploading
Previous Resource: XML READ / WRITE in ASP.net
Return to Discussion Resource Index
Post New Resource
Category: ASP.NET/Web Applications


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use