views:

40

answers:

2

On my page in the Page_Load event I add a collection of strings to the Context object. I have an HttpModule that will fire EndRequest and retrieve the collection of strings. What I then do is write out a script reference tag (based on the collection of strings) to the response. The problem is that the page reads the script reference but doesn't retrieve the contents of the file (I imagine because this is occurring in the EndRequest event). I can't fire the BeginRequest event because I won't have access to the Context Items collection.

I tried to also registering an HttpHandler which Processes the request of the script reference but I can't access the collection of strings in the Context.Items from there. Any suggestions?

Page_Load:

protected void Page_Load(object sender, EventArgs e)
    {
        Context.Items.Add("ScriptFile", "/UserControls.js");
    }

HttpModule:

public void OnEndRequest(Object s, EventArgs e)
    {
        HttpApplication app = s as HttpApplication;
        object script = app.Context.Items["ScriptFile"];
        app.Response.Write("<script type='text/javascript' src='" + script + "'></script>");
    }
A: 

First off, I'm fairly certain this is not a valid place to put tags.

Second, why are you re-inventing the wheel? You already have the ScriptManager and well-established methods of injecting script code into ASP.NET output. Why does this need to happen during EndRequest? This should probably be handled at the page level.

Bryan
A: 

If each reference points to a specific script, I would use the ClientScriptManager in Page_Load of each page.

if(!ClientScript.IsClientScriptIncludeRegistered("ScriptFile"))
{
     ClientScript.RegisterClientScriptInclude("ScriptFile", "/UserControls.js");
}

If you need to calculate the scripts to link in based on more than one key or some other factor not known in each page, then check out answer #2 in this question.

Mikael Svenson