0

How to call a JavaScript alert from a static method in C#?

I have tried the following code but the method does not get called.

 public static void WriteToErrorLog()
 {   
     Page mypage = new Page();
     ErrorMessage(mypage);                
 }
 public static void ErrorMessage(Page page)
 {
     page.ClientScript.RegisterStartupScript(typeof(Page), "alert", "<script type='text/javascript'>alert('Oops something went wrong, please try later...!!');</script>");
 }
10
  • 1
    What server tech are you using? ASP.Net/MVC? Commented Dec 20, 2016 at 10:22
  • 2
    Have you tried Response.Write("<script>alert('Oops something went wrong, please try later...!!');</script>"); Commented Dec 20, 2016 at 10:22
  • 1
    You're registering the script on a local instance of Page that disappears when it goes out of scope.. Commented Dec 20, 2016 at 10:23
  • 1
    A static method has no concept of the context (HTTP request) that is being run. Basically don't use a static method. Put code (not necessarily that code) in a basecontroller and inherit all controllers from that controller. Commented Dec 20, 2016 at 10:28
  • 2
    Possible duplicate of How to call Jquery function from C# Commented Dec 20, 2016 at 10:53

1 Answer 1

1

you can use the following code to get a reference to the current ScriptManager:

var currentScriptManager = System.Web.UI.ScriptManager.GetCurrent(page);

and then use it as per the following example:

currentScriptManager.RegisterClientScriptBlock(page.GetType(), "pagename", " ", "alert('ERROR')", true);
Sign up to request clarification or add additional context in comments.

8 Comments

You can't use this in a static method
@stuartd: indeed you can, he is already passing reference to the page.
@stuartd: and if he is not passing the page, he can get a reference to is by using the following line (Page)(HttpContext.Current.Handler)
@stuartd: thanks for the link: I've updated the code to the the page parameter instead of the this keyword.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.