Add Javascript File Programmaticaly in C#

Recently, i was trying to add a javascript on my page programmaticaly. First, i added a file named RedirectToHttps.js to my current project in VS 2008. Then i added some code like this:

private void AddHttpAutoRedirectScript()
  if (!ApplicationSettings.DevelopmentMode)
    string key = "redirectToHttp";
    string url = ResolveClientUrl("~/Site/Scripts/RedirectToHttp.js");
    Page.ClientScript.RegisterClientScriptInclude(key, url);

Just ignore !ApplicationSettings.DevelopmentMode, because it’s due to a specific condition in my current project. And then, I invoke this method on Page_PreInit event of the page.

It’s quite simple right ?! But i takes me half an hour before i can discover this solution… Hmm, poor me..


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s