0

right now I have a dropDownList which is a "Select" HTML control with "Option" elements and is already runat="server", here is the code:

<select name="webmenu" id="webmenu" class="fWidth" runat="server">
  <option value="calendar" data-image="TempImages/AldiBl.png">Aldi</option>
  <option value="shopping_cart" data-image="TempImages/Norma.png">Norma</option>
  <option value="cd" data-image="TempImages/AldiBl.png">Aldi</option>
  <option value="email" selected="selected" title="TempImages/AldiBl.png">Aldi</option>
  <option value="fam" data-image="TempImages/AldiBl.png">Aldi</option>
  <option value="games" data-image="TempImages/AldiBl.png">Aldi</option>
</select>

The list with its elements I can access from code behind but my problem is that I need to add the elements dinamically, the ones above are just an example, to do so I have a javascript function that adds the elements, here it is:

function showAccounts(names, images) {
  var namesArray = names.split(",");
  var imagArray = images.split(",");

  for (var ro = 0; ro < namesArray.length; ro++) {
    $('#menuName').append($("<option value='" + namesArray[ro] + "' data-image='" + imagArray[ro] + "'>" + namesArray[ro] + "</option>"));
  }
  return false;
}

The elements are well added and displayed but when accessed from code behind they do not exist inside the list which I can understand because they are created on client side so this is my question, how can I add elements with images to my "select" element from code behind so I can access them from code behind?

Many thanks in advance.

Hassan Abbas
  • 1,166
  • 20
  • 47
JCO9
  • 960
  • 1
  • 15
  • 24
  • [How to add a images in select list](http://stackoverflow.com/questions/2965971/how-to-add-a-images-in-select-list) – romi Jul 18 '16 at 09:39

1 Answers1

1

Try this:

    private ListItem CreateListItem(string value, string text, string dataImage) {
        ListItem li = new ListItem() { Value = value, Text = text };
        li.Attributes["data-image"] = dataImage;
        return li;
    }

    protected void Page_Load(object sender, EventArgs e) {
        List<ListItem> lis = new List<ListItem>();
        lis.Add(CreateListItem("test1", "blah1", "test.png"));
        lis.Add(CreateListItem("test2", "blah2", "test2.png"));
        lis.Add(CreateListItem("test3", "blah3", "test3.png"));

        if (!IsPostBack) {
            foreach (ListItem li in lis)
                webmenu.Items.Add(li);
        }
        else { 
            // persist custom attributes 
            for (int i = 0; i < webmenu.Items.Count; i++)
                webmenu.Items[i].Attributes["data-image"] = lis[i].Attributes["data-image"];
        }
    }

On post-back, you could then retrieve the values using webmenu.SelectedItem.Value and webmenu.SelectedItem.Attributes["data-image"]

Andy-Delosdos
  • 3,560
  • 1
  • 12
  • 25