.NET 1.0.NET4.5.NET 1.1.NET 3.0Design / GraphicsArchitect.NET4Advanced.NET 2.0.NET 3.5BeginnerIntermediateDevJavascriptWindows.NETASP.NET
Code behind JavaScript
Code behind JavaScript
Introduction
Sometimes we write a JavaScript in code behind to popup alert message and confirm messages. But it does not work as we thought. I think most of us are wondering why my code behind JavaScript is not working?
Background
This problem occurs while migrating 2.0 to 4.0 .NET version. It also depends on Ajax toolkit version.
Using the Code
- Use
the below code if your page is not using any Ajax tools or Script manager tag:
Public Shared Sub Show(ByVal message As String) Dim strScript As String = "<script type='text/javascript'>alert('" + message + "');</script>" Dim page As Page = TryCast(HttpContext.Current.CurrentHandler, Page) If page IsNot Nothing AndAlso Not page.ClientScript.IsClientScriptBlockRegistered("alert") Then page.ClientScript.RegisterClientScriptBlock(GetType(Alert), "alert", strScript) End If End Sub
- Use the below code if your page is using any Ajax tools and Script manager tag:
Public Shared Sub Show(ByVal message As String) Dim strScript As String = "<script type='text/javascript'>alert('" + message + "');</script>" Dim page As Page = TryCast(HttpContext.Current.CurrentHandler, Page) If page IsNot Nothing AndAlso Not page.ClientScript.IsClientScriptBlockRegistered("alert") Then ScriptManager.RegisterStartupScript(page, GetType(Alert), "alert", strScript, False) End If End Sub
Note
Should use ClientScript.RegisterClientScriptBlock
for non-Ajax pages and use ScriptManager.RegisterStartupScript
for
Ajax pages.
I feel it would be a good tip for developers who are currently migrating their .NET version.