Embed .js and .css to a web part

You can embed any resource (.jpg, .js, .css, etc) into a web part and provide it to the client without having to write an httphandler.   Here’s what you do:

1. Add the .js file to the project and mark as an embedded resource (See Build Action on properties tab).

2. Go into the AssemblyInfo.cs and add an entry.  It will look like this:
[assembly: WebResource (“Namespace.File.js”,“text/javascript”)]

Where Namespace is the namespace for your web part project and file.js is the name of your file.

3.  Inside OnPreRender, add the resource to the page.  This is done with the following code:

Page.ClientScript.RegisterClientScriptResource(GetType(), “Namespace.File.js”);

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s