Add javascript in VB.Net and C#

Submitted by:Jhon Smith

Date added:17 December, 2012

Category:VB.NET

Example code for Add javascript in VB.Net and C#

Tags: script manager

Code Snippet:

    Use the ScriptManager.RegisterStartupScript(). If you take a look at the methods of the ScriptManager class, you will observe that the methods to register client script to the page using the ClientScriptManager class, are also present in the ScriptManager class. So modify the code as shown below:
C#
protected void btnPostback_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script language='javascript'>");
sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");
sb.Append(@"lbl.style.color='red';");
sb.Append(@"</script>");

ScriptManager.RegisterStartupScript(btnPostback,this.GetType(), "JSCR", sb.ToString(),false);

}
VB.NET
Protected Sub btnPostback_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
sb.Append("<script language='javascript'>")
sb.Append("var lbl = document.getElementById('lblDisplayDate');")
sb.Append("lbl.style.color='red';")
sb.Append("</script>")

ScriptManager.RegisterStartupScript(btnPostback,Me.GetType(), "JSCR", sb.ToString(),False)

End Sub


C#
protected void Page_Load(object sender, EventArgs e)
{
lblDisplayDate.Text = System.DateTime.Now.ToString("T");
}

protected void btnPostback_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script language='javascript'>");
sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");
sb.Append(@"lbl.style.color='red';");
sb.Append(@"</script>");

if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb.ToString());
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
lblDisplayDate.Text = System.DateTime.Now.ToString("T")
End Sub

Protected Sub btnPostback_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
sb.Append("<script language='javascript'>")
sb.Append("var lbl = document.getElementById('lblDisplayDate');")
sb.Append("lbl.style.color='red';")
sb.Append("</script>")

If (Not ClientScript.IsStartupScriptRegistered("JSScript")) Then
ClientScript.RegisterStartupScript(Me.GetType(), "JSScript", sb.ToString())
End If
End Sub
 
 

Comments