We help IT Professionals succeed at work.

.NET update a form when page is closed

408 Views
Last Modified: 2012-07-16
I have a webform with a formview control.  The formview is used to allow users to amend data in the underlying dataset.  At the moment I have a link button calling the update command of the formview control for users to save the modified dataset. The users often forget to click the update button so I would like to know how I can trigger the update command when the page is closed so that the modified dataset is saved.  Can anyone give me some guidance on how this can be done in .net with c#
Comment
Watch Question

Roopesh ReddyIT Analyst
Top Expert 2012

Commented:
Hi,

You can invoke the Server side from JavaScript using Client Call backs / PageMethods!

On Browser close, you have an event - onbeforeunload which will be fired while closing the browser! You can make use of this event and achieve your goal!

Moreover you can check the below link, where i implemented a call back to server while closing the browser!

http://roopeshreddy.wordpress.com/2011/12/05/invoking-server-side-code-using-asp-net-ajax-client-callback-on-web-browser-close/

Hope it helps u...
Dear!!!

try using javascript function check if user closing the page without saving the page. prompt user a message "do you want to close this without saving?" on yes click do not save and no click save the page by calling server method.  

try this code.

<script type="text/javascript">
 
 
function closeit()
{
     event.returnValue = "Closit";
}
 
 
</script>
 
 
Call this on the body as:
<body onbeforeunload="closeit()">

or else follow this link.
http://www.eggheadcafe.com/articles/20010406.asp

Author

Commented:
Thanks you both for your suggestions.  I will work through them and get back to you

Author

Commented:
I haven't been able to make any progress with this.  All I want to do is safeguard my users from accidently navigating away from the page without saving the formview contents.  All I want to do is save the formview contents regardless of whether  any changes have been made or not. Something like the following pseudocode

onbeforeunload
{
Formview.updateitems(true);
}

It is not necessary for a warning dialogue or alert. it is OK to just save the Formview contents.

It seems that onbeforeunload is a client side event and Formview.Updateitems() is a server side event and never the twain shall meet, so can anyone help with this?

Author

Commented:
The Formview has a link button that will update the formview.  This appears to call a link to a javascript

javascript:__doPostBack('FormView1$UpdateButton0','')

If I could call this from the onbeforeunload event this would probably do the trick.  Can anybody tell me how to call this from onBeforeUnload?

Author

Commented:
I have tried this javascript function in the <Head> section

 <script type="text/javascript">

       window.onbeforeunload  = function () { __doPostBack("FormView1$UpdateButton0", "");};
 
</script>

I can see that the event is firing by inserting a return command and I get the dialog box about leaving the page but the postback is not firing.  Any help to find out why would be appreciated!
Technical Architect
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Apologies I have been snowed under and only now been able to look at this again.

I still have the same issue of how do I call the server side function.

I have modidfied your code above like so
<script type="text/javascript" src="\scripts\jquery-1.4.1.js"></script>
        <script type="text/javascript">
             $(document).ready(function () {
                $(window).unload(function () {
                     __doPostBack('FormView1$UpdateButton0', '')

               
           });
        });
        </script>

And this generates an error when the page is navigated away frommso the postback event seem to be firing OK but not saving the formview.  The error raised is

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

I've added the EnableEventValidation="true" directive to the page and tried to register the __doPostbackevent as follows

 protected override void Render(HtmlTextWriter writer)
    {
        ClientScript.RegisterForEventValidation( __doPostBack("FormView1$UpdateButton0", ""));
       
        base.Render(writer);
    }

But this gives an error that __doPostBack doesn't exist in the current context


Any ideas how to fix this?

Author

Commented:
I managed to get this working so I will close the question and award the points.  Unfortunately it has some unwanted side effects which means it doesn't work as anticipated.  The page I am trying to protect has a multiview set out as tabs with a menu to allow switching between tabs.  When the form is saved on window close it seems to cancel out the postback issued by the menu and it then becomes impossible to change views within the multiview. Ho Hum another day another dollar to fix this.

The code I used to get the form to save on window close was to but a button on the page and use the following code to call its onclick handler.

<script type="text/javascript" src="\scripts\jquery-1.4.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $(window).unload(function () {

                    document.getElementById('<%=hbtnSaveFormView1.ClientID%>').click();



                });
            });
        </script>

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.