C# – how to use javascript and css in WebPart

cnetsharepoint-2007visual-studio-2008web-parts

I am using SharePoint Server 2007 Enterprise with Windows Server 2008 Enterprise. I am using publishing portal template. I am developing using VSTS 2008 + C# + .Net 3.5 + ASP.Net. And I want to develop a WebPart, which refers css and javascript (.js) files. My question is (1) how to deploy css/javascript files and (2) how to write reference path (e.g. ../../themes from my code below) from webpart to refer to related css/javascript files?

BTW: the existing code of css/javascript/Webpart is from existing aspx code and I am migrating aspx code to a Webpart. The code works in aspx.

Currently my code looks like this,

<link type="text/css" href="../../themes/test.css" rel="stylesheet" />
<script type="text/javascript" src="../../test.js"></script>

Best Answer

You can use my HtmlHelper class.

class HtmlHelper
{
    public static void IncludeScript(Page page, String key, String location)
    {
        if (!page.ClientScript.IsClientScriptIncludeRegistered(key))
             page.ClientScript.RegisterClientScriptInclude(key, location);
    }

    public static void IncludeCSS(Page page, String src)
    {
        HtmlLink css = new HtmlLink();
        css.Href = src;
        css.Attributes["rel"] = "stylesheet";
        css.Attributes["type"] = "text/css";
        css.Attributes["media"] = "all";

        page.Header.Controls.Add(css);
    }
}