Adding Custom JavaScript

This topic describes how to add custom JavaScript to an existing custom control.

This project on Github contains the sample project described in this topic. You can view the project on Github instead of writing out the code, if you prefer.
K2Documentation.Samples.Extensions.SmartForms.CustomControl

To add a custom JavaScript file to a custom control, three things are needed:

  • The JavaScript file added as an embedded resource to the project
  • Enabling the embedded JavaScript file as a WebResource
  • Setting the ClientScriptAttribute value to point to the embedded .js resource file

Adding a custom JavaScript

  1. Add a new Script.js file as an embedded file to the project
  2. Edit the .js file as shown below 
    Copy

    .js file

    // The JavaScript file added as an embedded resource to the project

    (function ($, undefined) {
        $(document).ready(function () {
            alert('Java Script from Control!');
        });
    })
    (jQuery);
  3. In the custom control's server-side code file:
    1. Add an assembly WebResource attribute that points to the embedded JavaScript resource file,
    2. Set the ClientScript attribute to point to the embedded resource file.
      See the code snippet below for an example:
      Copy

      Example setting the ClientScript attribute

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.WebControls;

      // SourceCode namespaces used in the control
      using SourceCode.Forms.Controls.Web.SDK;
      using SourceCode.Forms.Controls.Web.SDK.Attributes;

      // Point to the javascript file for the control
      [assembly: WebResource("CustomControl.Script.js", "text/javascript", PerformSubstitution = true)]

      namespace CustomControl
      {
          // Link to the definition file and the script file for the class
          [ControlTypeDefinition("CustomControl.Definition.xml")]
          [ClientScript("CustomControl.Script.js")]
          class JavaScriptControl : BaseControl
          {
              protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
              {
                  writer.Write(" <b>JavaScript on Control</b>");
              }
          }
      }
  4. Build and deploy the custom control assembly
  5. Restart the IIS service and clear your browser cache
  6. In the K2 Designer refresh your View
  7. You will now see the result of the Javascript as displayed in a pop up