0

I'm trying to execute a javascript function from a C# class in an asp.net application. I'm using the ScriptManager. I have a class UpdateUI, which contains the following method:

public static void RunScript()
{
    try
    {
        if (HttpContext.Current != null)
        {
            Page currentPage = HttpContext.Current.Handler as System.Web.UI.Page;
            ScriptManager.RegisterClientScriptBlock(currentPage, currentPage.GetType(), "disableControls", "disableControls()", true);
        }
    }
    catch (Exception ex)
    {
    }
}

When I call UpdateUI.RunScript() from another static class, the HttpContent.Current is null. Any idea how should I go in order to be able to execute the scriptmanager from a class which is not code-behind?

John Willemse
  • 6,608
  • 7
  • 31
  • 45
krafo
  • 183
  • 5
  • 20
  • From where does the static class call this method? During a page's lifecycle? Otherwise it is `null` (e.g. from a webmethod). – Tim Schmelter May 08 '13 at 14:34
  • @TimSchmelter As far as I know in a WebMethod HttpContext.Current is available. I think I already did this to get Session data in a WebMethod. – Vitor Canova May 08 '13 at 16:07
  • @VitorCanova: As far as i know `HttpContext.Current.Handler` is not a `Page` in a webmethod so it's `null`. However, it was just an example. He has not mentioned if the static class is used during the lifecycle of a page. – Tim Schmelter May 08 '13 at 16:17
  • @TimSchmelter I agree. I mention that because Krafo said that `HttpContext.Current` is `null`, not the `Hanlder` part. This fact is strange to me. ;) – Vitor Canova May 08 '13 at 16:26

1 Answers1

0

Pass the HttpContext to the method within your static class. As Tim Schmelter's comment indicates, calling HttpContext.Current will fail if it's not done in response to an incoming request.

public static void RunScript(HttpContext context);
Lee Hiles
  • 1,125
  • 7
  • 9