I want to call javascript function from User Control using C#. For that i am trying to use
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "javascript:ShowPopup('Select a row to rate');", true);
but it is not wor开发者_如何学Goking for me. This works fine on the page. Can some one help me out how can i call javascript function at runtime using C#.
Thanks,
Try this.GetType() instead of typeof(string):
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertbox", "ShowPopup('Select a row to rate');", true);
The following is taken from working code, showing script being registered to fire from an asynchronous postback in an UpdatePanel
.
ScriptManager.RegisterStartupScript( this.upnl, this.upnl.GetType(), Guid.NewGuid().ToString(), "alert('test');", true );
If your code is not executed from inside an UpdatePanel
, it still should not be typeof(string)
; you should use the type of some container (typically the control itself).
Type: The type of the client script block. This parameter is usually specified by using the typeof operator (C#) or the GetType operator (Visual Basic) to retrieve the type of the control that is registering the script.
Im not sure if this is the best way to do it but for my user controls that use javascript i have a public string property on the user control and register it in the page.
// sudo code
eg. UserControl
{
public bool CustomBool
{
get
{
//logic
return value;
}
}
public string Javascript
{
get { return "javascript...."; }
}
}
in page
{
page load()
{
if (Usercontrol.CustomBool)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", UserControl.Javascript, true);
}
}
}
The downside for this is you have to remember to register the scripts on the page. it does work though
Try it without the "javascript:" in the script string:
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "ShowPopup('Select a row to rate');", true);
I find that the string given is embedded literally, so it's necessary to enclose it in a suitabie <script type='text/javascript' language='javascript'>
and </script>
精彩评论