Attaching JavaScript to the prototype of an ASCX client side instance

余生颓废 提交于 2019-12-13 03:46:56

问题


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

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


回答1:


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');


来源:https://stackoverflow.com/questions/6920985/attaching-javascript-to-the-prototype-of-an-ascx-client-side-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!