Grid Sorting navigate to Onbeforeunload Event

Hello Folks, my friend came to me with one issue like he has given window.onbeforeunload event to warn the user before leaving page but in that page 2-3 grids are there. So whenever he was doing sorting in grid onbeforeunload event fires up and warning message pop ups. This was happening because of postback on sorting. After two days hard work i got one solution. I don’t know why but i have literally give up on this. So never give up on anything just do your best with it ๐Ÿ™‚ . So i want to share that solution with you guys.

Below is my event on Notes.aspx page:

<script language="javascript" type="text/javascript">
        var needToConfirm = true;
        window.onbeforeunload = function () {
            if (needToConfirm) {
                var rslt = confirm('Are you want to save information?');
                if (rslt == true) {
                    //Here goes your code to save data.
                }
            }
        }
 </script>

So whenever we do sorting on grid it will fire up this event to prevent firing of this event we added few more code.

Below is modified code :

<script language="javascript" type="text/javascript">
        var needToConfirm = true;
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_pageLoaded(initPagers);

        function initPagers() {
            $(".grid-view").click(function () { needToConfirm = false; });
            $(".link").click(function () { needToConfirm = false; });
            
        }
        window.onbeforeunload = function () {
            if (needToConfirm) {
                var rslt = confirm('Are you want to save information?');
                if (rslt == true) {
                     //Here goes your code to save data.
                }
            }
            else
                needToConfirm = true;
        }
</script>

By using Sys.WebForms.PageRequestManager.getInstance() it will return instance of PageRequestManager and stored in variable prm. prm.add_pageLoaded(initPagers) will raised pageloaded event after all content on the page is refreshed, whether it was refreshed because of a synchronous postback or an asynchronous postback.

<asp:GridView ......  CssClass="grid-view"></asp:GridView>

initPagers() will check that grid views header clicked or not if it clicked it will change the flag using which we show warning message to user. And if needToConfirm is not true in else it will change it value. You can use other class to keep avoiding warning message, like we have used link in our code.

Hope it will help you. Don’t forget to share your review. Keep smiling ๐Ÿ™‚

Also readย Call code behind method from javascript asp.net

Leave a Reply