65.9K
CodeProject is changing. Read more.
Home

Code behind JavaScript

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Apr 18, 2014

CPOL
viewsIcon

15265

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.