Passing GridView Control IDs to JavaScript

2.2k views Asked by At

I'm trying to implement a call to a Javascript function that appears within a Gridview in each row. The code produces a button that can be clicked and brings up an Image Editor instance (Aviary by Adobe).

Because I don't have unique variable names then the same image is appearing each time, if I try to do this on a standalone page and change the Javascript variable names for each image the code works so I'm not sure what to do as I don't know how to make unique variable references.

I can't include the document.getElementByID parts inline as parameters to the function because I can't escape the single quotes.

The 3 javascript variables are

editImageControl editImageURL editImageFilename

<asp:TemplateField HeaderText="Edit Photo">
    <ItemTemplate>

        <asp:Image ID="editImage" runat="server" ImageUrl='<%# "http://images.foo.com/" & Eval("filename") %>' CssClass="noDisplay" />
        <script>
            var editImageControl = document.getElementById('<%# DirectCast(Container, GridViewRow).FindControl("editImage").ClientID%>');
            var editImageURL = document.getElementById('<%# DirectCast(Container, GridViewRow).FindControl("editImage").ClientID%>').src;
            var editImageFilename = '<%# Eval("filename") %>';
        </script>

        <!-- Add an edit button, passing the HTML id of the image and the public URL of the image -->
        <p><input type='image' runat="server" src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick="return launchEditor(editImageControl, editImageURL, editImageFilename);" /></p>

    </ItemTemplate>
</asp:TemplateField>
1

There are 1 answers

1
Philip Pittle On BEST ANSWER

When you bind editImageControl use Id instead of ClientId. Id will give you a very long and cumbersome id, but it will be unique for every element (it's the full path for the control within the page's control tree).

  var editImageControl = document.getElementById(
        '<%# DirectCast(Container, GridViewRow).FindControl("editImage").Id%>');

Another option is to set the editImage's ClientId when you define the control. This way JavaScript can access it correctly. I'm going to assume that filename is unique and is valid for storing as an html element's id (you might need to remove any path seperator or file extensions characters for this to work).

 <asp:Image ID="editImage" runat="server" ClientID='<%#Eval("filename")%>'
      ImageUrl='<%# "http://images.foo.com/" & Eval("filename") %>' 
      CssClass="noDisplay" />

Then you can use the same logic to set editImageControl:

var editImageControl = <%#Eval("filename")%>;