简体   繁体   中英

Call ASP.NET 2.0 Server side code from Javascript

I'm struggling with this for the past 3 days. I need to call asp.net serverside code from Javascript when the user closes the browser. I'm using the following code to accomplish this. In my asp.net form I have various validation controls. Even if there are some validation errors, When I close the form the server side code works perfectly in my development box(windows 7). But the same code doesnt work in my production environment(windows server).

Does it have something to do with the Validation summary or Validation controls. The button control has Causes validation set to false. So even if there is a validation error still my form will post back. Am I correct? I suspect the form is not getting post back to the server when there is a validation error. But i'm disabling all the validation controls in the javascript before calling the button click event. Can someone throw some light on this issue.

There are few blogs which suggests to use JQUERY, AJAX (Pagemethods and script manager).

        function ConfirmClose(e) {

        var evtobj = window.event ? event : e;
        if (evtobj == e) {
            //firefox
            if (!evtobj.clientY) {
                evtobj.returnValue = message;
            }
        }
        else {
            //IE
            if (evtobj.clientY < 0) {
                DisablePageValidators();
                document.getElementById('<%# buttonBrowserCloseClick.ClientID %>').click();
            }
        }
    }

function DisablePageValidators() {
        if ((typeof (Page_Validators) != "undefined") && (Page_Validators != null)) {
            var i;
            for (i = 0; i < Page_Validators.length; i++) {
                ValidatorEnable(Page_Validators[i], false);
            }
        }
    }


//HTML 
<div style="display:none" >
    <asp:Button ID="buttonBrowserCloseClick" runat="server" 
        onclick="buttonBrowserCloseClick_Click" Text="Button" 
        Width="141px" CausesValidation="False"  />


//Server Code
protected void buttonBrowserCloseClick_Click(object sender, EventArgs e)
{
    //Some C# code goes here
 }

Look at following links:

They describe how you can react on browser closing in JavaScript. With this you can initialize an ajax request from JavaScript to the server (with help of jQuery or any other JavaScript framework)!

http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm (works in Firefox and IE)

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM