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 -
JavaScript and CSS Support for custom scripts and custom controls:
- ECMAScript version: ES5
- CSS version: CSS3
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
- Add a new Script.js file as an embedded file to the project
- 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); - In the custom control's server-side code file:
- Add an assembly WebResource attribute that points to the embedded JavaScript resource file,
- Set the ClientScript attribute to point to the embedded resource file.
See the code snippet below for an example:CopyExample 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>");
}
}
} - Build and deploy the custom control assembly
- Restart the IIS service and clear your browser cache
- In the Designer refresh your View
- You will now see the result of the Javascript as displayed in a pop up