ASP.NET MVC ListBox - Client-Side API - Get Selected Item

  • 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
Get Selected Item
The ListBox control provides client-side properties / methods for setting / getting the selected item.

Use the selectedIndex client-side method to get / set the selected index.
Use the options collection to get the text / value of the selected item.
View - Aspx

    <% Html.Obout(new ListBox("ListBox1")
    {   
        Width = Unit.Pixel(300),
    }); %>
    
    <% Html.Obout(new OboutCheckBox("OboutCheckBox1")
    {
        Text = "Get Selected Item",
        OnClientClick = "return getSelectedItem();"
    }); %>	   
    
    
View - Razor

    @Html.Obout(new ListBox("ListBox1")
    {   
        Width = Unit.Pixel(300),
    })
    
    @Html.Obout(new OboutCheckBox("OboutCheckBox1")
    {
        Text = "Get Selected Item",
        OnClientClick = "return getSelectedItem();"
    })
    
    
JavaScript

    function getSelectedItem() {
        if (ListBox1.selectedIndex() != -1) {
            alert('Selected item: ' + ListBox1.options[ListBox1.selectedIndex()].text);
        } else {
            alert('No selected item.');
        }

        return false;
    }