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

Princa picture Princa · Apr 4, 2013 · Viewed 29.2k times · Source

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?

Answer

Joe Johnston picture Joe Johnston · Apr 4, 2013

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.