Timer控件考試倒計時源碼


前台:

<%@ 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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM