Reference ASP.NET control by ID in JavaScript?

前端 未结 9 1199
孤街浪徒
孤街浪徒 2020-11-28 09:25

When ASP.NET controls are rendered their ids sometimes change, like if they are in a naming container. Button1 may actually have an id of ctl00_ContentMai

9条回答
  •  [愿得一人]
    2020-11-28 10:27

    I don't think there's a single "best practice" for doing this. There's plenty of different pretty good practices. Here's ours:

    Every control which has client-side functionality renders a script block inline, directly below the markup for the control:

    
        control markup
    
    
    

    Each control has an accompanying JS like:

    var CustomControl = function(id) {
        this.control = document.getElementByID(id);
        this.init();
    };
    
    CustomControl.prototype.init = function() {
        //do stuff to wire up relevant events
    };
    

    In the codebehind, we do something like:

    class CustomControl : Control
    
    override void Render(HtmlTextWriter writer)
    {
        writer.WriteBeginTag("span");
        writer.WriteAttribute("id", this.ClientID);
        writer.Write(HtmlTextWriter.TagRightChar);
        //write control markup
        writer.WriteEndTag("span");
        writer.WriteBeginTag("script");
        writer.WriteAttribute("type", "text/javascript");
        writer.Write(HtmlTextWriter.TagRightChar);
        writer.Write(
            string.Format("new CustomControl('{0}');", this.ClientID)
        );
        writer.WriteEndTag("script");
    }
    

提交回复
热议问题