ASP.NET如何从public static方法调用customercript

时间:2012-01-14 08:56:51

标签: asp.net static-methods

我将在公共静态方法中使用以下ClientScript函数(VS2010,C#),但它会给我一些错误(我想将它用于带有“_parent”目标的响应重定向

                ClientScript.RegisterStartupScript(GetType(), "Load", "<script type='text/javascript'>window.parent.location.href = '" + a + "'; </script>");

Error   37  An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get' 

Error   38  An object reference is required for the non-static field, method, or property 'object.GetType()'    

感谢

1 个答案:

答案 0 :(得分:6)

您不能在static methods(基本上是任何实例)中使用实例属性(ClientScript)或方法(GetType())。

删除static关键字,它应该有效:

public void SomeMethod()
{
     ClientScript.RegisterSomeScript("Load", 
        "<script>....</script>");
}

评论后编辑:

或者,如果您需要该方法在静态类中是静态的,则将Page对象作为参数传递:

public static class ScriptRegistar
{
    public static void RegisterSomeScript(Page page)
    {
         page.ClientScript.RegisterStartupScript("Load", 
        "<script>.........</script>");
    }
}

用法(在页面代码隐藏中):

public void Page_Load(Object sender, EventArgs e)
{
     ScriptRegistar.RegisterSomeScript(this);
}

旁注:ClientScript.RegisterStartupScript有两个参数:脚本的密钥和脚本文本,因此不需要GetType()