Search code examples
asp.net-coreblazorblazor-server-sideasp.net-core-8

Inject a string into a Blazor/HTML element when there's no key=value property


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.


Solution

  • If you wanna render selected attribute via

    @(kvp.Key == SelectedValue ? "selected" : "")
    

    It will report an error:

    Failed to execute 'setAttribute' on 'Element': '@(kvp.Key' is not a valid attribute name.
    

    HTML element attributes are conditionally rendered based on the .NET value. If the value is false or null, the attribute isn't rendered. If the value is true, the attribute is rendered minimized. So if you wanna shortcut the first process, You can use this method to render the selected attribute by condition.

    @foreach (var kvp in ListOfValues)
            {
                <option value="@kvp.Key" selected="@(kvp.Key==SelectedValue)">
                    @kvp.Value
                </option>
            }