Search code examples
c#asp.netdatalist

How could i select multiple images in datalist, without using any checkbox?


I have a datalist

<asp:DataList ID="dlst1" runat="server" RepeatDirection="Horizontal" RepeatColumns="5"
                                CellSpacing="8">
     <ItemTemplate>
           <asp:ImageButton ID="Image" runat="server" ImageUrl='<%#"~/Controls/handler1.ashx?FileName=" +DataBinder.Eval(Container.DataItem, "FilePath") %>'
                                        OnCommand="Select_Command" CommandArgument='<%# Eval("Id").ToString() +";"+Eval("FilePath")+";"+Eval("Index")+";"+Eval("FileName") %>' />

      </ItemTemplate>
  </asp:DataList>

How could i select multiple images?


Solution

  • I would probably use jQuery to select images at client side and maintain the selection in the hidden field. For example,

    <asp:DataList ID="dlstImage" runat="server" RepeatDirection="Horizontal" RepeatColumns="5" CellSpacing="8">
         <ItemTemplate>
               <img class="selImg" alt='<%# Eval("Id") %>' src='<%# ResolveUrl("~/Controls/ShowImage.ashx?FileName=") + Eval("FilePath") %>' />
    
          ...   
          </ItemTemplate>
    </asp:DataList>
    <input runat="server" id="imageSelection" />
    

    Use with below JS

    $(document).ready(function() {
       var store = $('#<%= imageSelection.ClientID %>');
       var selection = store.val().length > 0 ? store.val().split(",") : [];
       var images = $('.selImg');
       // Set the selection
       images.each(function() {
         var id = $(this).attr('alt');
         if (jQuery.inArray(id, selection) >= 0) {
            $(this).addClass('selected'); // selected CSS class will decide UI for selected image
         }
       });
    
       // add click handler
       images.click(function() {
         $(this).toggleClass('selected'); // toggle selection UI
         // modify selection
         selection = [];
         images.find('.selected').each(function() {
           selection.push($(this).attr('alt'));
         });
         // update the store
         store.val(selection.join(","));
       });
    });
    

    This is a basic (untested) code that should get you started. There are many improvements that you can try - e.g. setting a focus rectangle on image hive, adding a keyboard support, using html5 data attribute to store id instead of alt attribute etc.