前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick"> </asp:Timer> <asp:Label ID="lbtime" runat="server" Text="Label"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>
cs代码:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Timers; public partial class _Default : System.Web.UI.Page { int num = 0; protected void Page_Load(object sender, EventArgs e) { num = 10; } //触发Timer控件的Timer1_Tick事件实现考试倒计时功能 protected void Timer1_Tick(object sender, EventArgs e) { this.index--; //考试时间到了 if (this.index<= 0) { //设置Timer控件不可见 this.Timer1.Enabled = false; this.lbtime.Text = this.index / 60 + "分" + this.index % 60 + "秒"; ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "updateScript", "alert('答题超时,请关闭本页面重新进入!');window.opener=null;window.open('','_self');window.close();", true); } else { //显示考试剩余时间 this.lbtime.Text = this.index / 60 + "分" + this.index % 60 + "秒将停止考试,请及时“提交”试卷,否则试卷作费成绩无效!"; } } /// <summary> /// 定义在线考试总时间变量index, /// 并设置读写属性 /// </summary> private int index { get { object o = ViewState["index "]; return (o == null) ? num : (int)o; } set { ViewState["index "] = value; } } }
注意事项:web.config文件,必须加入以下代码:否则ajax失效:
<httpHandlers> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/> </httpHandlers>