Search code examples
javascriptasp.netascxprototype-programming

Attaching JavaScript to the prototype of an ASCX client side instance


How can I code my ASCX control so that I can give an ID and from the browser run some javascript such as

$find('myASCXControlClientId')

and the returned object, has a class with a prototype with my custom javascript methods that can be called on said instance of the control?

The Telerik controls such as RadTreeView can do this for instance

enter image description here

The control they fetch with Javascript has a prototype with some neatly defined methods. How can I do this with ASCX?


Solution

  • The RadControl you show above might have been implemented as a ScriptControl instead of a UserControl (which has the extra .ascx file).

    You might already know that the ScriptControl class does exactly what you are asking and when you do $find(elementid) it returns the actual javascript object of the control.

    The problem that I hate with the ScriptControl is that you basically have to build your control's DOM elements programmatically by adding .NET objects like Table and Label to your control's ChildControls collection during Load or PreRender

    One of the options that I have seen work is to create a ScriptControl that houses your properties and methods, and then wrap that with an ascx UserControl:

    ScriptControl Example:

    public class MyScriptControl : System.Web.UI.ScriptControl
    {
        public string MyProperty { get; set; }
    
        protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            //your implementations
        }
    
        protected override IEnumerable<ScriptReference> GetScriptReferences()
        {
            //your implementations
        }
    }
    

    UserControl Example:

    public partial class MyUserControl : System.Web.UI.UserControl
    {        
        protected override void OnLoad(EventArgs e)
        {
            this.MyLabel.Text = this.MySpecialScriptControl.MyProperty;
    
            base.OnLoad(e);
        }
    }
    

    .ascx Example:

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Example.ascx.cs" Inherits="Example" %>
    
    <div>
        <asp:Label id="MyLabel" runat="server" />
        <my:MyScriptControl id="MySpecialScriptControl" runat="server" />
    </div>
    

    This should allow you to get both control over your ascx markup and the ability in javascript to do something like:

    var myScriptControl = $find('MySpecialScriptControl');