If your code is within an AJAX updatepanel use this:
Dim scriptCommand As String = "alert('This transaction has been deleted');"
scriptCommand += ""
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "MyScript", scriptCommand, True)
If your code is not within an AJAX updatepanel, use this:
Dim scommand As String = "<script language=javascript> alert('This transaction has been deleted');</script>"
Page.RegisterStartupScript("MyScript", scommand)
Add small javascript functions to controls dynamically:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
btnAdd.Attributes.Add("onClick", "alert('This js function was added on the fly to this control!');")
btnAdd.Attributes.Add("style", "background-color:yellow")
End Sub
<asp:Button id="btnAdd" runat="server" Text="Add Record" />
Using Larger Javascript Functions
So how do you go about putting entire JavaScript functions in your code? There are a couple of ways to accomplish this task and we will take a look at the RegisterStartupScript and the RegisterClientScriptBlock methods.
One of the first options available is to register script blocks using one of the .NET classes for this purpose. The first is the RegisterStartupScript method. This class would be best used when you have a JavaScript function that you want to initiate when the page is loaded. For an example of this, create an ASP.NET page in Visual Studio .NET that contains two buttons. Button1 and Button2 should be the IDs of the two buttons. Then place the following code within the Page_Load event.
RegisterStartupScript
Page.RegisterStartupScript("MyScript", _
"<script language=javascript>" & _
"function AlertHello() { alert('Hello ASP.NET'); }</script>")
Button1.Attributes("onclick") = "AlertHello()"
Button2.Attributes("onclick") = "AlertHello()"
RegisterClientScriptBlock Method
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Page.RegisterClientScriptBlock("MyScript", _
"<script language=javascript>" & _
"alert('This transaction has been deleted')" & _
"</script>")
End Sub
Keeping JavaScript in a Separate File (.js)
Keeping JavaScript functions in a separate file (a .js file) is highly recommended. Once they are in a separate file and part of a project, the file can be imported into a page using some of the methods already described.
For instance, a .js file can be included in an ASP.NET page using the following code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Page.RegisterClientScriptBlock("MyScript", "<script language=javascript src='MyJavaScriptFile.js'>")
End Sub