如何从代码隐藏中刷新asp页面?C#
我在这方面是新手,我的英语也很差。无论如何: 我正在尝试设置一个计时器,以便在报告中有任何新记录时刷新页面。显然,我的计时器工作正常,因为当我调试它时,它会进入函数如何从代码隐藏中刷新asp页面?C#,c#,asp.net,timer,reload,code-behind,C#,Asp.net,Timer,Reload,Code Behind,我在这方面是新手,我的英语也很差。无论如何: 我正在尝试设置一个计时器,以便在报告中有任何新记录时刷新页面。显然,我的计时器工作正常,因为当我调试它时,它会进入函数Timer1\u Tick,但它不会刷新我的页面 代码如下: System.Timers.Timer Timer1 = new System.Timers.Timer(); Timer1.Interval = 10000; Timer1.Elapsed += Timer1_Tick; Timer1.Enabled = true; 及
Timer1\u Tick
,但它不会刷新我的页面
代码如下:
System.Timers.Timer Timer1 = new System.Timers.Timer();
Timer1.Interval = 10000;
Timer1.Elapsed += Timer1_Tick;
Timer1.Enabled = true;
及
也
函数刷新页面()
{
window.location.reload()
}
编辑:
这不起作用的原因是,一旦响应从服务器发送到客户端,服务器就不能再修改响应,因此无法注册启动脚本。您必须记住服务器端和客户端之间的区别 相反,您可以用JavaScript实现在客户端运行的计时器,如中所述
但是,这并不理想,因为现在您的页面将再次请求页面的整个HTML。那是一大笔开销。相反,您应该只刷新所需的数据。我在中介绍了各种技术,其中讨论了UpdatePanel、AJAX轮询和使用Signal。注意:我特别建议不要使用UpdatePanel。它们既复杂又低效。我建议您使用Ajax来执行此操作 但实现这一点的简单方法是使用Asp.Net定时器和更新面板组件 在.aspx中:
<asp:ScriptManager runat="server" id="ScriptManager1"/>
<asp:UpdatePanel runat="server" id="UpdatePanel1">
<ContentTemplate>
<asp:Timer runat="server" id="Timer1" Interval="10000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:Label runat="server" Text="Page not refreshed yet." id="Label1">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
asp:ScriptManager组件是使用更新面板所必需的。更多信息。asp.net提供页面服务后,将停止与服务器的通信。页面加载完成后,无法将通知从代码隐藏推送到客户端* 如果您只是想在一段时间后重定向用户,请检查客户端上的时间,如: C#: JavaScript
<script type="text/javascript">
function RefreshPage()
{
setTimeout(function(){
window.location.reload();
}, 10000);
}
</script>
函数刷新页面()
{
setTimeout(函数(){
window.location.reload();
}, 10000);
}
否则,您可以随时创建从客户端到服务器的请求
- 例如,有WebSocket和SSE,但如果您只是想用它们刷新页面,它们并不是最好的解决方案
<asp:ScriptManager runat="server" id="ScriptManager1"/>
<asp:UpdatePanel runat="server" id="UpdatePanel1">
<ContentTemplate>
<asp:Timer runat="server" id="Timer1" Interval="10000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:Label runat="server" Text="Page not refreshed yet." id="Label1">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString();
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "RefreshPage()", true);
<script type="text/javascript">
function RefreshPage()
{
setTimeout(function(){
window.location.reload();
}, 10000);
}
</script>