Reference ASP.NET control by ID in JavaScript?

前端 未结 9 1198
孤街浪徒
孤街浪徒 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:

    <span id="something_crazy_long">
        control markup
    </span>
    <script type="text/javascript">new CustomControl('something_crazy_long');</script>
    

    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");
    }
    
    0 讨论(0)
  • 2020-11-28 10:29

    I do something similar to Rex M except to avoid multiple script tags I use a function in my page base class to register the controls I am going to use clientside, then spit them out to html inside 1 script tag.

    You could even subclass your controls to automatically register with the function or use a boolean property to set whether you are going to use them clientside.

    0 讨论(0)
  • 2020-11-28 10:31

    This post by Dave Ward might have what you're looking for:

    http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/

    Excerpt from article:

    Indeed there is. The better solution is to use inline ASP.NET code to inject the control’s ClientID property:

    $get('<%= TextBox1.ClientID %>')
    

    Now the correct client element ID is referenced, regardless of the structure of the page and the nesting level of the control. In my opinion, the very slight performance cost of this method is well worth it to make your client scripting more resilient to change.

    And some sample code by Dave from the comment thread of that post:

    <script>
      alert('TextBox1 has a value of: ' + $get('<%= TextBox1.ClientID %>').value);
    </script>
    

    The comment thread to the article I linked above has some good discussion as well.

    0 讨论(0)
提交回复
热议问题