Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Code behind JavaScript

0.00/5 (No votes)
18 Apr 2014 1  
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

  1. 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  
  2. 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here