Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET how to call clientscript from public static method

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

like image 676
Ali_dotNet Avatar asked May 12 '26 01:05

Ali_dotNet


1 Answers

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.

like image 168
nemesv Avatar answered May 14 '26 23:05

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!