3

我有一个如下的 class.cs 文件,但我的“Page.ClientScript”有一个错误,它说“非静态字段、方法或属性‘System.Web.UI.Page’需要对象引用.ClientScript.get'”。所以我想知道 page.clientscript 是否不能在 class.cs 中使用?使用任何其他方法来代替 page.clientscript 吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;
using System.Data;
using System.Web.Script.Services;


public class SessionExpired
{

    public SessionExpired()
    {
        string csname = "timeoutWarning";
        Type cstype = this.GetType();
        if (!Page.ClientScript.IsStartupScriptRegistered(cstype, csname))
        {
             string strconfirm = "<script>" +
                "window.setTimeout('SessionTimeOutHandler()', 60000);" +
                "function SessionTimeOutHandler() { " +
                "alert('Your login session is expired');" +
                "window.location='../Processing.aspx';" +
                "}</script>";
            Page.ClientScript.RegisterStartupScript(cstype, csname, strconfirm, false);
        }

    }
}
4

1 回答 1

6

您遇到了问题,因为看起来您使用的类不是从System.Web.UI.Page. 但是,只要您有权访问HttpContext,您就可以说:

using System.Web;
using System.Web.UI;

...

var page = HttpContext.Current.CurrentHandler as Page;

if( page == null ){
     // throw an exception, something bad happened
}

// now you have access to the current page...
page.ClientScript.RegisterStartupScript();
于 2012-08-10T10:42:04.500 回答