开发者

how to use javascript and css in WebPart?

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 b开发者_运维技巧elow) 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>


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);
    }
}


For javascript, there is ClientScriptManager.RegisterClientScriptInclude

There is not an equivalent method for css, but you can:

  1. provide a list of class names, and suggest a css file, but not include one yourself

  2. use embedded resources

  3. add controls to the header:

(As I did here):

HtmlLink link = new HtmlLink();
link.Href = "Cases/EditStyles.css";
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(link);

Best practice says you should not include the css as I did above (or in embedded resources). You should use method number 1 above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜