如何实现ASP.Net组合服务器控件的ClientInstanceName属性

时间:2012-07-17 18:27:22

标签: c# asp.net devexpress custom-server-controls

如何在我自己的服务器控件中实现DevExpress用于其控件的ClientInstanceName属性?

ClientID属性是只读的。这是否意味着我必须等到生成HTML然后替换name属性?

有没有办法在c#中执行此操作,还是必须在JavaScript中执行此操作?

提前致谢。

1 个答案:

答案 0 :(得分:1)

以下是我提出的建议(欢迎任何建议或改进):

            private String _ClientInstanceName;

            /// <summary>
            /// Gets or Sets the client instance name.
            /// </summary>
            [
            Bindable(true), Category("Client-Side"),
            DefaultValue(""), Description("The ClientInstanceName can be used to reference this control on the client.")
            ]
            public String ClientInstanceName
            {
                get
                {
                    return _ClientInstanceName;
                }
                set
                {
                    _ClientInstanceName= value;
                }
            }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            //Register startup script for creating JavaScript reference to this server control object.
            if (this.ClientInstanceName.Length > 0) { registerClientInstanceName(this.ClientInstanceName, this.ClientID); }
        }

        /// <summary>
        /// Create a JavaScript reference to the Object with ClientID using the ClientInstanceName property.
        /// Based on: http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
        /// </summary>
        /// <param name="ClientInstanceName"></param>
        private void registerClientInstanceName(String ClientInstanceName, String ClientID)
        {
            // Define the name and type of the client scripts on the page.
            String csname1 = "ClientInstanceNameScript";
            Type cstype = this.GetType();

            // Get a ClientScriptManager reference from the Page class.
            ClientScriptManager cs = Page.ClientScript;

            // Check to see if the startup script is already registered.
            if (!cs.IsStartupScriptRegistered(cstype, csname1))
            {
                StringBuilder cstext1 = new StringBuilder();
                cstext1.Append("<script type=text/javascript>");
                cstext1.Append("window['" + ClientInstanceName + "']=document.getElementById('" + ClientID + "');");
                cstext1.Append("</script>");

                cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
            }
        }