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开发者_StackOverflow社区 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
精彩评论