views:

566

answers:

1

Hello everyone,

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>

thanks in advance, George

+1  A: 

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.

Gabriel McAdams
Why I need to use client script manager to register it in order to use it in WebPart? Why I can not just reference css/javascript file from some relative path, just like what we did in html/aspx code?
George2
Technically, you can. It will work (the path must relative to the page). But what if you use the web part in multiple pages and the path is different?
Gabriel McAdams