Click here to Skip to main content
12,070,351 members (53,404 online)
Click here to Skip to main content
Add your own
alternative version

Stats

7.7K views
6 bookmarked
Posted

Code behind JavaScript

, 18 Apr 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Raju_B
Technical Lead
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionAre you sure? Pin
Sanjay K. Gupta18-Apr-14 19:16
memberSanjay K. Gupta18-Apr-14 19: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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160208.1 | Last Updated 18 Apr 2014
Article Copyright 2014 by Raju_B
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid