I need to construct a <select>
list with an optional selected item. Currently I'm having to write out two versions depending on whether the selected
property of my dictionary item is true.
<InputSelect>
@foreach (var kvp in ListOfValues)
{
if (kvp.Key == SelectedValue)
{
<option selected value="@kvp.Key">@kvp.Value</option>
}
else
{
<option value="@kvp.Key">@kvp.Value</option>
}
}
</InputSelect>
However I was hoping to shortcut this process because if additional attributes are required (such as disabled
or class
it becomes ridiculously complex. Looking around for tutorials I assumed this might work, but it doesn't...
<InputSelect>
@foreach (var kvp in ListOfValues)
{
<option @(kvp.Key == SelectedValue ? "selected" : "") value="@kvp.Key">
@kvp.Value
</option>
}
</InputSelect>
Is there a way to add strings into HTML elements when there isn't a property=value combination?
Further clarity
I can successfully skip if the conditional check and just use <InputSelect @bind-Value="@SelectedValue">
, but this question also relates to aspects such as disabled
which don't generally render with =value
.