Register javascript inside User Control using C #

I want to call a javascript function from User Control using C #. For this I am trying to use

ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "javascript:ShowPopup('Select a row to rate');", true); 

but it does not work for me. This works well on the page. Can someone help me how can I call the javascript function at runtime using C #.

Thanks,

+4
source share
5 answers

The following is taken from the working code: it shows that the script is registered to activate the asynchronous postback in the UpdatePanel .

 ScriptManager.RegisterStartupScript( this.upnl, this.upnl.GetType(), Guid.NewGuid().ToString(), "alert('test');", true ); 

If your code is not executed from within the UpdatePanel , it still should not be typeof(string) ; you must use the type of some container (usually the control itself).

Type: Type of client script. This parameter is usually specified using a type operator (C #) or a GetType operator (Visual Basic) to get the type of control that the script registers.

+4
source

Try this.GetType () instead of typeof (string):

 ScriptManager.RegisterStartupScript(this, this.GetType(), "alertbox", "ShowPopup('Select a row to rate');", true); 
+5
source

I'm not sure if this is the best way to do this, but for my custom controls using javascript, I have a public row property in the user control and register it on the page.

// sudo code

eg. Usercontrol

  { public bool CustomBool { get { //logic return value; } } public string Javascript { get { return "javascript...."; } } } 

On the page

 { page load() { if (Usercontrol.CustomBool) { ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", UserControl.Javascript, true); } } } 

The disadvantage of this is the need to remember the scripts on the page. it works though

+1
source

Try this without "javascript:" in the script line:

 ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "ShowPopup('Select a row to rate');", true); 
0
source

I find that the specified string is inserted literally, so you need to wrap it in a suitable <script type='text/javascript' language='javascript'> and </script>

0
source

Source: https://habr.com/ru/post/1336470/


All Articles