Tuesday, November 28, 2006

How to add JavaScript and CSS file declaration in ASP.NET 2.0 head tag

Code example in C# that show how to add JavaScript and CSS file declaration to ASP.NET runat server tag:

private const string JavaScriptIncludeTemplate = "script language='JavaScript' src='{0}' type='text/javascript' /script";

string includeLocation;
includeLocation = System.Web.VirtualPathUtility.ToAbsolute("~/JS/Test.js");

// Check that we have header runat=server on page
if ((System.Web.UI.HtmlControls.HtmlHead)Page.Header != null)
{
// Look if file declaration not already exist in page
if (((System.Web.UI.HtmlControls.HtmlHead)Page.Header).FindControl(key) == null)
{
LiteralControl include = new LiteralControl(String.Format(JavaScriptIncludeTemplate, includeLocation));
include.ID = key;

// Add the file declaration to page
// You can also use Controls.AddAt(addAt, include) to control the order of the JS file registration.
((System.Web.UI.HtmlControls.HtmlHead)Page.Header).Controls.Add(include);
}
}

JavaScript actsAsAspect


The idea is that you run actsAsAspect() on any JavaScript object,
and then your object receives 3 extra methods:

  1. before()
  2. after()
  3. around()

You then can use those methods to setup the callbacks you need.


The Code:
function actsAsAspect(object) {
object.yield = null;
object.rv = { };
object.before = function(method, f)
{
var original = eval("this." + method);
this[method] = function()
{
this.rv[method] = f.apply(this, arguments);
if (this.rv[method] == false)
return false;
return original.apply(this, arguments);
};
};
object.after = function(method, f)
{
var original = eval("this." + method);
this[method] = function()
{
this.rv[method] = original.apply(this, arguments);
return f.apply(this, arguments);
}
};
object.around = function(method, f)
{
var original = eval("this." + method);
this[method] = function() {
this.yield = original;
return f.apply(this, arguments);
}
};
}

Example: Applying actsAsAspect() to window


actsAsAspect(window);
function haha() { return "HA Ha ha ha..."; }
after('haha', function() { alert(this.rv['haha']); });
haha();


Full information can be found:

http://beppu.lbox.org/articles/2006/09/06/actsasaspect