ASP.NET how to call clientscript from public static method

青春壹個敷衍的年華 提交于 2019-12-14 01:19:28

问题


I'm going to use following ClientScript function (VS2010,C#) in a public static method, but it gives me some errors (I want to use it for response redirect with "_parent" target

                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()'    

thanks


回答1:


You cannot use instance properties (ClientScript) or methods (GetType()) inside a static methods (basically anything instance).

Drop the static keyword and it should work:

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

EDIT after comment:

Or if you need that the method is static in a static class pass the Page object as a parameter:

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

Usage (inside a page codebehind):

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

Side note: ClientScript.RegisterStartupScript takes two arguments: the key for the script, and script text, so there is no need for the GetType() there.



来源:https://stackoverflow.com/questions/8861196/asp-net-how-to-call-clientscript-from-public-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!