简体   繁体   中英

Call a code behind function from javascript in aspx

I have a page where a javascript will be triggered when the user closes the browser tabs / browser window. Language is in c# thanks.

im using window.onbeforeunload, something along the line like this:

<script type="text/javascript">


    window.onbeforeunload = myFunction;


function myFunction()
{
    //call my function here
}

the code behind function will be a simple function for now, so no input parameters or return value are needed. So i'll just like to know how to call my function (eg: public void callMyFunction())

There are variety mechanisms to call your code-behind function(s). You could use an Ajax Call , Page Methods, ASP.NET Client Callbacks , or even trigger a code-behind handler using an invisible ASP.NET button .

Try the sample code below:

<html>
<head>
    <script src="scripts/jquery-1.4.4.min.js" type="text/javascript"></script>

    <script type="text/javascript" language="javascript">
        windown.OnUnload(){ function(){ $("#Btn_Click").click();}};
    </script>

</head>
<body>
...

 <asp:Button ID="Btn_Click" runat="server" Text="ButtonClick" onClick="Btn_Click" />
...
</body>
</html>

hope it helps !!!

By using Ajax you can access code behind method from javascript . Try this code.

<script  type="text/javascript">
     classname.methodname();
    </script>

In code behind page: in page load you need to register follwing code...

pageload()
{
      AjaxPro.Utility.RegisterTypeForAjax(typeof(pagename), this.Page);
}



[AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
    public void methodname()
    {
    ..........
    ........
    }

Here classname is code behind page class name

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