How to use <%=control.ClientID%> in server control with embedded JS file

29,886

Instead of the buttons name set a very specific CSS class name:

<asp:Button ID="btnMyGroovy" runat="server" CssClass="VerySpecific" Text="Action" />

Then use your jQuery Selector to get $('.VerySpecific') rather than the control name. Remember that items can have more than one class association. :)

You could make the selection more precise by selecting your server control CSS class eg..VerySpecificContainer then selecting the instance of .VerySpecific contained by the control.

Share:
29,886
Princa
Author by

Princa

Test Test Test

Updated on December 31, 2020

Comments

  • Princa
    Princa over 3 years

    I am creating a server control in a library project, which has javascript code, the javascript code need to get a button's ID, so I used <%= button.ClientID %>. Then I embed the javascript code as a file in the library project and use ScriptManager to add the script in CreateChildControls().

    Dim sm = ScriptManager.GetCurrent(Me.Page) 
    sm.Scripts.Add(New ScriptReference("xxx.js", "LibraryProjectName"))   
    

    But when I run the page, it has a jquery parse error:invalid expression term '>'. So I am guessing the code has been generated but server doesn't convert <%= button.ClientID %> into generated ID format. So what should I do in this case?

  • Princa
    Princa about 11 years
    ok, that would be great the server won't change the ID automatically, but you just have to be careful with the duplicated ID.