0

When you are coding in an aspx page you can do something like this:

<html>
  <head>
    <script type="text/javascript">
      $(document).ready(function () {
        var chkEnable = $get("<%= chkEnable.ClientID %>");
        alert(chkEnable);
      });
    </script>
  </head>
  <body>
    <form runat="server">
      <asp:CheckBox ID="chkEnable" runat="server" />
    </form>
  </body>
</html>

But the only way I have found to use javascript in a web part is to use a ScriptLink that imports the file. Example:

<SharePoint:ScriptLink ID="ScriptLink5" runat="server" Name="myPorject/js/myCustomScript.js" Localizable="false" LoadAfterUI="true"/>
<asp:CheckBox ID="chkEnable" runat="server" />

Is there any way that I could reproduce the functionality from my first example in a web part? Anything that I do must be able to be installed entirely through a wsp onto a system that I have no other access to. Any solution must be implemented entirely through the wsp.

  • by wsp do you mean sandbox or farm solutions? – djeeg Apr 18 '11 at 5:17
  • sorry, farm solutions. – Abe Miessler Apr 18 '11 at 15:07
1

ScriptLink is the recommended way if you're using a Farm solution. You can also add inline scripts to the WebPart (not the best way) or manually add your script tags to the WebPart.

Also take use of the Script-On-Demand (SOD) features that is available in SharePoint 2010: Loading Script in SharePoint 2010 (Dallas Tester).

To make the variable "dynamic"; add inline JavaScript code to your Web Part and just set the variable name/value there. Then use an external JavaScript file to host your logic.

  • Ok, so the external JS file will have access to that variable once I create it? Do I need to load them in a specific order or anything? – Abe Miessler Apr 18 '11 at 15:07
  • If the variable is defined inline, then it will always be available before any external JS files. Use the SOD features to call your external script from inline code, so that you are sure that the file is loaded and ready. – Wictor Wilen MCA MCM MVP Apr 18 '11 at 19:57
0

What about writing out to a literal using code behind? The can be a user control in a web part, which would be deployed as a wsp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.