Click here to Skip to main content
15,892,927 members
Articles / Web Development / ASP.NET
Tip/Trick

Invoke JavaScript dynamic from server side

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


Written By
Software Developer (Senior)
Switzerland Switzerland
👨 Senior .NET Software Engineer

🚀 My Open Source Projects
- Time Period Library 👉 GitHub
- Payroll Engine 👉 GitHub

Feedback and contributions are welcome.



Comments and Discussions

 
SuggestionThe name should be escaped Pin
Akram El Assas23-Mar-12 12:10
Akram El Assas23-Mar-12 12:10 
Hi,

Special characters in the name are interpreted by the browser.

For example, If you type the name groove'', the popup does not appear because the quotes are not escaped.

But, If you type groove\'\' as a name you will see groove'' in the popup.

If you write groove'); alert('coucou'); // as a name, you will see a popup with the name groove and If you click OK in the first popup you will see a coucou popup.

To resolve this issue, the name must be ascaped before to be passed to the alert function. You can use for example, Adam.JSGenerator Library[^].

Adam.JSGenerator allows you to write code that produces JavaScript snippets in a more readable and maintainable way. Instead of having to write tedious string concatenation code, interlined with String.Format and StringBuilder.Append lines, you use a fluent syntax to produce an object structure that produces the JavaScript output that you need.

Kind regards,
AnswerRe: The name should be escaped Pin
Jani Giannoudis24-Mar-12 6:39
Jani 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.