Include javascript file in sharepoint visual web part

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

And I put below line in ascx file to link to this file

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

and then in the ascx.cs file, and I use the methods defined in this file, for example,

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

But it does not work, it does not display the restriction window ... I refer to the wrong path. Please help me....

+6
source share
2 answers

To reference the javascript file from the 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 map of mapped layouts to the Visual Web Part project and place the scripts folder in the default folder, which I think is the name of the project. Following this model ensures that the javascript file will always be updated during deployment. The "Name" property in the above tag is just the path to the javascript file relative to _layouts, something like "/_layouts/ProjectName/Scripts/myjavascript.js".

Like FYI, if you want to use CSS, there is also a SharePoint tag: CssRegistration. I find that these are the 2 that I use the most.

+9
source

You should put your javascript file in the layout folder and use the SharePoint:ScriptLink :

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

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

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

+2
source

Source: https://habr.com/ru/post/894777/


All Articles