So after extensive search, I found that in order to trigger a javasript function, we could do this:
<script>
function foobar()
{
alert("foobar");
}
</script>
Dim strScript As String = "<script language='javascript' id='myClientScript'>foobar();</script>"
Page.RegisterStartupScript(“callTest”,strScript)
However, the Page.RegisterStartupScript seem to be working only under the Page_load function....
When I put it in a Sub, like this:
Sub Test
Dim strScript As String = "<script language='javascript' id='myClientScript'>foobar();</script>"
Page.RegisterStartupScript(“callTest”,strScript)
End Sub
This won't work. As I link the above function to an asp button. I triggered the button, but nothing happens. So is there anyway to trigger javaScript function conditionally from asp.net? From a Sub function instead of on every page_load?
Thanks!!
You should represent this line
Dim strScript As String = "<script language='javascript' id='myClientScript'>foobar();</script>"
as
Dim strScript As String
strScript = "<script language='javascript' id='myClientScript'>foobar();</script>"
If you want to call javascript for asp.net button click, you can use OnClientClick
attribute with a client side function OnClientClick="buttonClick()"
:-
<asp:button id="Button1"
runat="server"
OnClientClick="buttonClick()"
Text="Click!" />
The javascript injected using the RegisterStartUpscript method is executed when the page is first loaded. Try using the RegisterClientScriptBlock method when you need to inject and execute javascript after the
Type t = this.GetType();
if (!ClientScript.IsClientScriptBlockRegistered(t, "myClientScript"))
{
ClientScript.RegisterClientScriptBlock(t,"myClientScript", sb.ToString());
}
Not sure if it will work inside an updatepanel though
Below is the JavaScript function I am using and have used on numerous web applications where I work. On this specific example, I am comparing the clients IP address to a predetermined IP address on our network, and if the clients IP doesn't match, I display a message box that then informs the user that their specific computer terminal is not permitted to make these specific requests.
Dim ipAdd as string = nothing
ipAdd = Request.ServerVariables.Item("REMOTE_ADDR")
If ipAdd <> "###.###.###.###" then
ClientScript.RegisterClientScriptBlock(Page.GetType, "Script", "<script language='javascript'>alert('This terminal is not permitted to submit requests.');</script>")
End If
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.