Click here to Skip to main content
Click here to Skip to main content

Invoke JavaScript dynamic from server side

, 22 Mar 2012
Rate this:
Please Sign up or sign in to vote.
A simple ASP.NET control to invoke JavaScript code dynamic from the server side.

Introduction

ASP.NET provides the class ScriptManager to invoke JavaScript from server side code. In some dynamic scenarios (AJAX, Windows) ScriptManager isn't applicable, because the dynamically loaded JavaScript will not be parsed by the page. The control ScriptLabel can be used for such a scenario.  

Background

ScriptLabel is inherited from the ASP.NET Label and stores the JavaScript in its Text property.

// ------------------------------------------------------------------------
public class ScriptLabel : Label
{

  // ----------------------------------------------------------------------
  public bool IsPermantent { get; set; }

  // ----------------------------------------------------------------------
  public override string Text
  {
    get { return base.Text; }
    set
    {
      if ( !string.IsNullOrEmpty( value ) )
      {
        if ( !value.StartsWith( scriptBegin, StringComparison.InvariantCultureIgnoreCase ) )
        {
          value = scriptBegin + value;
        }
        if ( !value.EndsWith( scriptEnd, StringComparison.InvariantCultureIgnoreCase ) )
        {
          value = value + scriptEnd;
        }
      }
      base.Text = value;
    }
  } // Text

  // ----------------------------------------------------------------------
  protected override void OnLoad( EventArgs e )
  {
    base.OnLoad( e );
    if ( !IsPermantent )
    {
      Text = null;
    }
  } // OnLoad

  // ----------------------------------------------------------------------
  // members
  private const string scriptBegin = "<script type='text/javascript'>";
  private const string scriptEnd = "</script>";

} // class ScriptLabel

By default the JavaScript isn't permanent and will be cleared on any page post back. To keep the JavaScript permanently, you can set the IsPermanent property to true.  

Using the code  

After placing a ScriptLabel on a web form (.aspx), assign in your code behind the JavaScript to its Text property. Here are some examples showing some possible scenarios:  

// ----------------------------------------------------------------------
protected void CheckName( object sender, EventArgs e )
{
  string name = NameEdit.Text;
  if ( string.IsNullOrEmpty( name ) )
  {
    ScriptLabel1.Text = "alert('please enter a name');";
  }
  else
  {
    ScriptLabel1.Text = string.Format( "alert('name: {0}');", NameEdit.Text );
  }
} // CheckName

// ----------------------------------------------------------------------
protected void ChangePageColor( object sender, EventArgs e )
{
  Random random = new Random();
  KnownColor[] names = (KnownColor[])Enum.GetValues( typeof( KnownColor ) );
  KnownColor randomColorName = names[ random.Next( names.Length ) ];
  Color color = Color.FromKnownColor( randomColorName );
  ScriptLabel2.Text = string.Format( "changeBackground('#{0}');",
    ColorTranslator.ToHtml( color ) );
} // ChangePageColor

// ----------------------------------------------------------------------
protected void CloseWindow( object sender, EventArgs e )
{
  ScriptLabel3.Text = "window.close();";
} // CloseWindow

The JavaScript invoked by the sample ChangePageColor is permanently and remains on any subsequent server request.

History   

22nd March 2012: Initial version  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jani Giannoudis
Software Developer (Senior)
Switzerland Switzerland
Jani is Co-founder of Meerazo.com, a free service which allows to share resources like locations, things, persons and their services in a cooperating group of people.

Comments and Discussions

 
SuggestionThe name should be escaped PinmemberAkram El Assas23-Mar-12 12:10 
AnswerRe: The name should be escaped PinmvpJani Giannoudis24-Mar-12 6:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web03 | 2.8.140721.1 | Last Updated 22 Mar 2012
Article Copyright 2012 by Jani Giannoudis
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid