Search code examples
jqueryasp.netuser-controlsname-manglingname-matching

How to handle elements ID when using jQuery and ASP.NET user controls


I have some user controls in ASP.NET that I am using as simply HTML, that is, without any code-behind.

I one control I have an element with a fixed ID and I am pointing it with some jQuery client scripts. For example:

<div id="slider-section"></div>

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        var slider = $('#slider-section');
        // ... do something with the jQuery Object
    });
</script>

This works very good without any problem. But there is a side effect with this. In fact, if I add two instances of the same user control on my page I will have two elements with the same ID.

Which is in your opinion a good way to handle a situation like this?

thanks


Solution

  • If you added runat="server" to your simple HTML controls then they would have a page-unique ClientID like all other server controls. No codebehind code is needed.

    E.g.

    <div id="slider-section" runat="server"></div>
    
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            var slider = $('#<%=slider-section.ClientID %>');
            // ... do something with the jQuery Object
        });
    </script>