Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include javascript file in sharepoint visual web part

I am using sharepoint 2010 and developing a visual web part. I had javascript functions on the ascx file and they all used to work file.Now I have moved them to a single javascript.js file and deployed it to the _layouts folder on server.

And I have put the below line on the ascx file to reference to that file

<script src="/sites/xxxxx/_layouts/customwebparts/javascript.js" type="text/javascript"> </script>

and then on the ascx.cs file and I am using the methods defined in this file for eg.,

      btnCancel.Attributes.Add("onclick", "{return Action(Cancel the form?)};");

But it is not working, it is not displaying the confimration box ...Am I referencing the wrong way. Please help me ....

like image 460
Janet Avatar asked Aug 11 '11 00:08

Janet


2 Answers

To reference a javascript file from within a SharePoint Visual Web Part you need to use the SharePoint:ScriptLink tag (example below):

<SharePoint:ScriptLink ID="<someid>" runat="server" Name="/_layouts/...<Path>"></SharePoint:ScriptLink>

I add a layouts mapped folder to my Visual Web Part project and place a scripts folder within the default folder, which I believe is the projects name. Following this model ensures that the javascript file is always kept up-to-date during deployment. The 'Name' property in the above tag is just the path to the javascript file relative to _layouts, so something like "/_layouts/ProjectName/Scripts/myjavascript.js".

As an FYI if you want to use CSS as well there is a SharePoint:CssRegistration tag as well. I find these are the 2 that I use the most.

like image 183
Matt Klepeis Avatar answered Sep 20 '22 00:09

Matt Klepeis


You should put your javascript file in the Layout mapped folder and use the SharePoint:ScriptLink tag:

    <SharePoint:ScriptLink id="ScriptLink1" runat="server" Localizable="false" Name="some-layout-subfolder/file.js" />

If you have a file not found error you should check that the Localizable attribute is set to false and from Visual Studio, in the properties of the js file, Build Action should be set as Content and Deployment Type should be TemplateFile.

Check here for more details: http://blog.netgloo.com/2014/06/19/include-javascript-and-css-files-in-your-sharepoint-2010-visual-web-part/

like image 21
Andrea Avatar answered Sep 22 '22 00:09

Andrea