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:

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
 // The JavaScript file added as an embedded resource to the project

(function ($, undefined) $(document).ready(function () alert('Java Script from Control!');
>);
>)
(jQuery);
  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:
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(" JavaScript on Control");
>
>
>