Search code examples
javascriptc#asp.netstaticwebmethod

Call Javascript function from C# static web method (page method)


I used:

ScriptManager.RegisterStartupScript(this, GetType(), "", "MyJSFunction('parameter')", true);

to reach the MyJSFunction function in JavaScript from Page_Load and it worked fine. Now I'm in need of calling lets say the same function but from a static web method, but I get these 2 errors on this & GetType():

this: Keyword 'this' is not valid in a static property, static method, or a static field initialized.

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

I tried to re-format the code like this:

ScriptManager.RegisterStartupScript((Page)(System.Web.HttpContext.Current.Handler), ((Page)(System.Web.HttpContext.Current.Handler)).GetType(), "", "MyJSFunction('parameter')", true);

No errors shown, but it doesn't reach the JavaScript function.

Can anyone help?


Solution

  • Call the JavaScript function upon successful completion (callback) of the call to the web method in your JS code. You can't "call" client-side code from the code behind; you can register a JS function call as a "startup script" but not here as a call to a web method does not involve a postback of the page nor does it cause Page_Load to run.