Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Invoke JavaScript dynamic from server side

5.00/5 (1 vote)
22 Mar 2012CPOL 11.8K   55  
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.

C#
// ------------------------------------------------------------------------
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:  

C#
// ----------------------------------------------------------------------
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)