Click here to Skip to main content
15,393,377 members
Articles / Web Development / ASP.NET
Tip/Trick
Posted 22 Mar 2012

Stats

10.6K views
55 downloads
2 bookmarked

Invoke JavaScript dynamic from server side

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
22 Mar 2012CPOL
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)

Share

About the Author


Comments and Discussions

 
SuggestionThe name should be escaped Pin
Akram El Assas23-Mar-12 12:10
MemberAkram El Assas23-Mar-12 12:10 
AnswerRe: The name should be escaped Pin
Jani Giannoudis24-Mar-12 6:39
MemberJani Giannoudis24-Mar-12 6:39 

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.