Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pull the clientID of an asp:button inside an asp:listview for use with jQuery?

Tags:

jquery

c#

asp.net

I'm attempting to do something which should be relatively simple. I'm using a ListView to show a number of items, using the ItemTemplate. Inside the ItemTemplate I have a div surrounding the full item, so that I can highlight on a hover event, (being handled already by jQuery).

What I would like to do is have the click event on the div fire a button to open a details view for that specific item. The problem I'm having is pulling back the ClientID for that button while using jQuery. I've tried the:

$('#<%= Button1.ClientID %>')

route, but that doesn't work, as the Button doesn't exist when the page loads.

The basic code is as follows:

<asp:listview>
 <itemtemplate>
  <td runat="server">
   <div class="container">
    <asp:linkbutton id="Button1" runat="server" text="View Details" />
     fun and exciting stuff here...
   </div>
  </td>
 </itemtemplate>
</asp:listview>

Any suggestions or help are much appreciated!

like image 308
riceboyler Avatar asked Dec 09 '22 22:12

riceboyler


2 Answers

Why don't you just give those linkbuttons a specific css class?

<asp:linkbutton id="Button1" runat="server" text="View Details" CssClass="detailsButtons" />

Then in jquery just select the class to assign them all in one call.

$(".detailsButtons").click( function() { .... } );

If that doesn't work because the objects aren't made at that time, you can use the new live() method in jquery. It will assign the events to any dynamically added elements as well.

Hope this helps

like image 76
Jab Avatar answered Dec 13 '22 13:12

Jab


Instead of using the scriptlet:

$('#<%= Button1.ClientID %>')

use a binding expression:

$('#<%# Button1.ClientID %>')

Notice the difference is the # instead of the =.

Binding expressions are evaluated when the data is bound, and therefore your expression will evaluate in the context of the current data item. Scriptlets are evaluated when the page is rendered (at the very end of the page lifecycle), and evaluate in the context of the page, not a particular data item.

like image 41
Trent Avatar answered Dec 13 '22 14:12

Trent