Does Page.ClientScript available been used in clas

2019-07-16 05:16发布

I have a class.cs file as following, but there is an error for my "Page.ClientScript", which said "an object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get'". So I. wonder is the page.clientscript is not available to used in class.cs? Any other method to use instead of 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);
        }

    }
}

标签: c# class
1条回答
手持菜刀,她持情操
2楼-- · 2019-07-16 05:55

You are having problems because it looks like you are using a class which doesn't derive from System.Web.UI.Page. However, as long as you have access to HttpContext, you can just say:

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();
查看更多
登录 后发表回答