Search code examples
c#drop-down-menublazorblazor-server-sideselecteditem

I can read out in my Blazor server app, the selected item of a select box. Is it also possible to read out the index number of the selected item?


With my code below I can read out the selected item in my select box (@selected_type). Is it also possible to read out something like a index number of the selected item? With index number I mean is it the first, second , third option value, of the total option values in the select list. Is that possible?

<td class="td_DiagBuff_data" max-width="150">
    <select value="@selected_type" @onchange="@(e => { func_MD_type(e,index);  })">
        <option value="">--------</option>
        <option value="">NC-Machine Data</option>
        <option value="">CH-Machine Data</option>
        <option value="">AX-Machine Data</option>
        <option value="">DR-Machine Data</option>
        <option value="">SD-Machine Data</option>
        <option value="">R-Parameter</option>
        <option value="">GUD</option>

    </select>
</td>

Solution

  • Whenever I need to do this I move my <options> into a collection or dictionary of KeyValuePair with a unique identifier (If using a dictionary then Key should be the unique field).

    List<KeyValuePair<string, string>> _machineDataList = new List<KeyValuePair<string, string>>()
    {
        new KeyValuePair<string, string>(string.Empty, "--------"), // String.Empty will force required validation attribute.
        new KeyValuePair<string, string>("0", "NC-Machine Data"),
        new KeyValuePair<string, string>("1", "CH-Machine Data"),
        .
        .
        .
    
    };
    

    Your markup becomes

    <select @bind="selected_type">
        @foreach(KeyValuePair<string,string> pair in _machineDataList)
        {
            <option value="@pair.Key">@pair.Value</option>
        }
    </select>
    

    And access the selections like this

    var selection = _machineDataList.FirstOrDefault(d => d.Key== selected_type);