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;
}
}
protected override void OnLoad( EventArgs e )
{
base.OnLoad( e );
if ( !IsPermantent )
{
Text = null;
}
}
private const string scriptBegin = "<script type='text/javascript'>";
private const string scriptEnd = "</script>";
}
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 );
}
}
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 ) );
}
protected void CloseWindow( object sender, EventArgs e )
{
ScriptLabel3.Text = "window.close();";
}
The JavaScript invoked by the sample ChangePageColor
is permanently and remains on any subsequent server request.
History
22nd March 2012: Initial version