ASP.NET MVC ListBox - Client-Side API - Add/Delete Items

  • Alfreds FutterkisteALFKI
  • Antonio Moreno TaqueríaANATR
  • Around the HornAROUT
  • Berglunds snabbköpANTON
  • Berglunds snabbköpBERGS
  • Blauer See DelikatessenBLAUS
  • Blondesddsl père et filsBLONP
  • Bólido Comidas preparadasBOLID
  • Bon app'BONAP
  • Bottom-Dollar MarketsBOTTM
 
Add Item

Remove Item
The ListBox control provides client-side methods for adding / removing items.

  • Use the add method of the options collection to add items to the list.

    Usage: ListBox1.options.add(text [, value] [, index]);
    - text - the text of the new item;
    - value - the value of the new item (same as text if not specified);
    - index - the position in the list where the new item should be added
          (if not specified, the item will be added at the end of the list);

  • Use the remove method of the options collection to remove items to the list.

    Usage: ListBox1.options.remove(index);
    - index - the index of the item to be removed;
View - Aspx

    <% Html.Obout(new ListBox("ListBox1")
    {
        Width = 250
    }); %>	 
    
    <% Html.Obout(new OboutTextBox("OboutTextBox1")
    {   
    }); %>
    
    <% Html.Obout(new OboutButton("OboutButton1")
    {   
         OnClientClick = "return addItem();"
    }); %>      
    
    
View - Razor

    @Html.Obout(new ListBox("ListBox1")
    {
        Width = 250
    })
    
    @Html.Obout(new OboutTextBox("OboutTextBox1")
    {   
    })
    
    @Html.Obout(new OboutButton("OboutButton1")
    {   
         OnClientClick = "return addItem();"
    })
    
    
JavaScript

    function addItem() {
        if (OboutTextBox1.value() != '') {
            ListBox1.options.add(OboutTextBox1.value());
            OboutTextBox1.value('');
        } else {
            alert('Please type the text.');
        }

        return false;
    }

    function removeItem() {
        var selectedIndex = ListBox1.selectedIndex();
        clearSelection();

        if (selectedIndex != -1) {
            ListBox1.options.remove(selectedIndex);
        } else {
            alert('Please select an item.');

        }

        return false;
    }

    function clearSelection() {
        ListBox1.selectedIndex(-1);
        ListBox1.value('');
    }