views:

306

answers:

2

Hey there!

So, I'm trying to do what I thought was a simple task... But I'm not getting anywhere... All I want to is to get some .js and .css files loaded by my WebPart. I'm using VS2008 + WSPBuilder. I've googled a lot about this but I couldn't find a decent answer. What I would like to know:

  • Where in the directory structure should I place those files? (eg. 12/TEMPLATE/OTHER? 80/wpresources/assembly_name?)

  • How can I reach those files? (using a relative path? getting the full path by some method?)

  • And finally, how can I add those files to the page's <head>?

Thanks in advance.. I've lost all my morning in these questions and i'm considering a career change! ;)

A: 

Ok, after two cigarettes and more efficient google searches I found the solution.. Hope this helps someone in the same trouble as I was!

  • The right place to those extra files is in 12/TEMPLATE/LAYOUTS/1033/yourapp/

  • If they are in this place, the path to those files is /_layouts/1033/yourapp/yourjs.js

  • If you want to add a JavaScript file to the head of the page, place this code in the CreateChildControls() method:

string scriptPath = "/_layouts/1033/yourapp/yourjs.js";
if(!this.Page.ClientScript.IsClientScriptBlockRegistered(scriptPath))
    this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), scriptPath,
    "<script language=\"javascript\" src=\"" + scriptPath + "\">");
  • If you want to add a CSS file to the head of the page, place this code in the CreateChildControls() method:
CssLink cssLink = new CssLink();
cssLink.DefaultUrl = "/_layouts/1033/yourapp/yourcss.css";
this.Page.Header.Controls.Add(cssLink);

Well, hope you found this helpfull!

Pedro MM
Erm - don't think this is quite right.
Ryan
+1  A: 

Resources should go in the wpresources folder.

If an admin deploys your web part to the BIN directory then this folder will be in something like

http://server/site/wpresources/YourWebPart/

which will be mapped to something like

C:\Inetpub\wwwroot\wss\VirtualDirectories\80\wpresources\YourWebPart

If an admin deploys to the GAC then it will be

http://server/_wpresources/WebPartStrongName/

mapped to

C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/wpresources/WebPartStrongName

To find out the path that you need at runtime you should use WebPart.ClassResourcePath

So modifying your code

string scriptPath = this.ClassResourcePath + "/yourjs.js";
if(!this.Page.ClientScript.IsClientScriptBlockRegistered(scriptPath))
    this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), scriptPath,
"<script language=\"javascript\" src=\"" + scriptPath + "\">");

MSDN - Creating a Web Part with Client-side Script

Ryan