Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET
Tip/Trick

Code behind JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
18 Apr 2014CPOL 14.7K   6   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:
    C++
    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:
    C++
    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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAre you sure? Pin
Sanjay K. Gupta18-Apr-14 18:16
professionalSanjay K. Gupta18-Apr-14 18:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.