When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, February 11, 2004

Adding Client-Side Message Boxes in your ASP.NET Web Pages, Part 2
By Tim Stall


  • Read Part 1

  • In Part 1 we examined how to add confirm message boxes in an ASP.NET Web page. In this final part, we'll look at how to display alert message boxes.

    - continued -

    Displaying Alert Message Boxes
    Besides having prompting the user to confirm that they want to perform an action, we might also want to notify the user of some server-side behavior. For example, if there was some server-side error and the data entered wasn't correctly saved, we might want to use an alert message box to inform the user. Or perhaps when attempting to add the data provided into the database, we deduced that the provided data was duplicate data. The question becomes, coming back from the server to the client, how would we alert the user with a message box?

    Traditionally we would do this with JavaScript in the html of the page by creating an onload event that generated a message box. However like the previous case, ASP.NET provides us additional methods to handle all this from the code-behind without having to hard code HTML ourselves.

    What we want to do is register a client script block with the ASP.NET Web page. More specifically, we want this to run when the page starts up on the client. Again it's our lucky day, as the ASP.NET Page class provides a RegisterStartupScript() method for that very purpose.

    Typically what will happen is the user will submit his data, we'll do some processing, and then realize that we need to alert the user of some unexpected behavior. Therefore, we'll probably need to add this RegisterStartupScript() method call in the Button Web control's server-side Click event handler. The code for this might look something like:

    Private Sub BtnSave_Click(ByVal sender As System.Object, _
                  ByVal e As System.EventArgs) Handles BtnSave.Click
    
      'Generates the message:
      Dim strMessage As String
      If (Me.CheckBox1.Checked()) Then
         strMessage = "The data was saved."
      Else
         strMessage = "The data was NOT saved."
      End If
    
      'finishes server processing, returns to client.
      Dim strScript As String = "<script language=JavaScript>"
      strScript += "alert(""" & strMessage & """);"
      strScript += "</script>"
    
      If (Not Page.IsStartupScriptRegistered("clientScript")) Then
         Page.RegisterStartupScript("clientScript", strScript)
      End If
    End Sub
    

    This code first generates the message by checking field values (in this case if a CheckBox1 CheckBox Web control was checked or not) and building the message appropriately. However note that the message could be generated from any server-side process, such as the return value of a business object, or based upon the results of a stored procedure or database query.

    Once we have the message, we can build the client-side JavaScript script block. The RegisterStartupScript() method takes two string inputs: a key, identifying the script block being registered, and the actual script itself. Notice that the second input parameter, the client-side script, includes both the <script> tag, and the JavaScript code to run (alert('...');). Before calling RegisterStartupScript() it is prudent to first check to make sure that the script block hasn't already been registered. (In our simple example above, it clearly couldn't have already been registered, but if you are registering a script block based on, say, values in a DataGrid, there might be multiple records that would cause the script block to be rendered. A check to IsStartupScriptRegistered() quickly determines if a startup script has already been registered or not.)

    In the screen below, the user has selected the checkbox and then clicked the save button. The server then generates the necessary JavaScript block, registers it, and displays it upon returning the page to the client.

    An alert message box is displayed upon postback.

    Like the previous sample, we can also abstract this functionality to a Utilities class. For this method, we need to pass in a Page class instance (since the RegisterStartupScript() and IsStartupScriptRegistered() methods are methods of the Page class), along with the string to display in the alert message box and the key name by which to register the script.

    Public Class Utilities
      Public Shared Sub CreateMessageAlert(ByRef aspxPage As System.Web.UI.Page, _
                               ByVal strMessage As String, ByVal strKey As String)
        Dim strScript As String = "<script language=JavaScript>alert('" _
                                            & strMessage & "')</script>"
    
        If (Not aspxPage.IsStartupScriptRegistered(strKey)) Then
            aspxPage.RegisterStartupScript(strKey, strScript)
        End If
      End Sub
    End Class
    

    The original page could then call the CreateMessageAlert() method like so:

    Private Sub BtnSaveUtil_Click(ByVal sender As System.Object, _
               ByVal e As System.EventArgs) Handles BtnSaveUtil.Click
            	
       'Generates the message:
       Dim strMessage As String
       If (Me.CheckBox1.Checked()) Then
         strMessage = "The data was saved."
       Else
         strMessage = "The data was NOT saved."
       End If
    
       'Call separate class, passing page reference, to register Client Script:
       Utilities.CreateMessageAlert(Me, strMessage, "strKey1")
    End Sub

    Notice that when calling the CreateMessageAlert() method we pass in Me for the Page class instance. This is because the code-behind class is inherited from the Page class, so we can just pass in the code-behind class reference. The second parameter is the message to display in the alert message box and the third input parameter provides the key name for the script block.

    Conclusion
    In this article we looked at how to add client-side message boxes to your ASP.NET application. Adding confirm message boxes is as simple as adding an onclick attribute to the Button Web control's Attributes collection. Displaying an alert message box on page load involves calling the Page.RegisterStartupScript() method, passing in the complete JavaScript block that should be performed on page load.

    Happy Programming!

  • By Tim Stall


    Attachments

  • Download a Demonstration of these Examples

  • Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES