在ASP.NET C#中的页面加载上触发OnUnload代码 [英] OnUnload code firing on pageload in ASP.NET C#
本文介绍了在ASP.NET C#中的页面加载上触发OnUnload代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用c#
在asp.net中准备一个网页我希望在页面加载时执行某些代码,并在页面卸载时执行其他一些代码。我的代码如下:
I am preparing a webpage in asp.net using c#
I want certain code to be executed on page load and some other code to be executed on page unload. My code is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//code to be executed on page load when user enter the page
}
}
// Other code for execution depending on user requirement
protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);
// code to be executed on user leaves the page
}
我的问题是卸载的代码在pageload本身被触发,而我希望只有页面加载代码在页面加载时触发pageunload代码仅在用户离开页面时触发。
请通过告知我在代码中缺少的内容来帮助我
非常感谢帮助
My problem is that the code for unload gets fired on pageload itself whereas I expect only pageload code to fire at page load and pageunload code to fire only when user leaves the page.
Kindly help me by advising what I am missing in the code
Many thanks for help
推荐答案
With AutoEventWireup which is turned on by default on a page you can just add methods prepended with Page_event and have ASP.NET connect to the events for you.
In the case of Unload the method signature is:
protected void Page_Unload(object sender, EventArgs e)
So you need to write:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//code to be executed on page load when user enter the page
}
}
// Other code for execution depending on user requirement
protected void Page_UnLoad(object sender, EventArgs e)
{
// code to be executed on user leaves the page
}
Actually Page_UnLoad event is rasied when the page is rendered and loaded completely at the end of its page life cycle.It is not just like you have done through form_closing event in windows form application.Instead you can detect browser close event and then call server side event using ajax.As shown like below
<script type="text/javascript">
( function (){
这篇关于在ASP.NET C#中的页面加载上触发OnUnload代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文