Friday, April 2, 2010

SharePoint Web Part and JavaScript--Add script to web part

ASP.NET controls are not limited to the server controls, you also can insert JavaScript in the ASPX page, just like we do in the HTML file. In order to improve user experiment in richer interface, JavaScript is your indispensable tool.In the Web 2.0 age, good user experiment is essential to your site. Users don’t like refreshing the pages again and again.You also can use the ASP.NET AJAX if you are on the MS side, but you also has other choices, like your own script or other three party library. In ASP.NET,
there is a ClientScript object in Page class, it manage the script on the page. We can use it to manage our scripts too.
Add a block of script
string ScriptKey = "myScript";
string EmbeddedScript ="<script language=javascript>function fun(){alert('hello world'); }</script> ";
if(!Page.IsClientScriptBlockRegistered(ScriptKey ))
    Page.RegisterClientScriptBlock(ScriptKey ,EmbeddedScript );

Link a external file
You also can link a external file to your web part. Linking a external file to the web part is very similar to embed a block of code to web part. First, you need put your file under the 12 hive folder, like layout. The only think you need notice is the location of your file. If you do not what doe the location look like in a SharePoint ASPX page, you can just open a page , right click, view source, find the default script’s location.
string ScriptKey = "myScript";
string EmbeddedScript ="<script language='javascript' src='your file'></script> ";
if(!Page.IsClientScriptBlockRegistered(ScriptKey ))
     Page.RegisterClientScriptBlock(ScriptKey ,EmbeddedScript );

Embed a file to DLL file
Sometimes, if you want to prevent your resources, such as images,css,Javascript, from being touched. You can embed them into a DLL. A ASP.NET provides the special URL of “WebResource.axd” to provide these files.
At first, you need add your script file to your project, then change the the Build Action like below:

Next, open the AssemblyInfo.cs file (usually appears under the ‘properties’ folder). In here we need to add a reference to the file and tell the compiler what it’s MIME type is. You can check the exactly location using the Reflector.

[assembly: WebResource("***.MyScript.js", "text/javascript")]
hen you add the script file like below.
string scriptUrl=this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "Location of your file"));
this.Page.ClientScript.RegisterClientScriptInclude("MyScript", scriptUrl)
The only issue that need to be mentioned about embedding the file to the DLL is the performance. Getting the file from the file system should be faster than exacting from the DLL file.

No comments:

Post a Comment