Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Last active November 7, 2020 08:03
Show Gist options
  • Select an option

  • Save JerryNixon/8db0588b89da876c321d3557cd4cdf28 to your computer and use it in GitHub Desktop.

Select an option

Save JerryNixon/8db0588b89da876c321d3557cd4cdf28 to your computer and use it in GitHub Desktop.
Blazor troubles with rendering <option/>
@using Microsoft.AspNetCore.Components.Rendering
<EditForm Model="@Model">
<InputSelect class="form-control" @bind-Value="Model.Selection">
@{ MakeOption(__builder, "John"); }
@{ MakeOption(__builder, "Jack"); }
@{ MakeOption(__builder, "Mark"); }
</InputSelect>
</EditForm>
@code {
// https://stackoverflow.com/a/57840040/265706
// https://visualstudiomagazine.com/articles/2019/10/02/blazor-gotchas.aspx
public class Record
{
public string Selection { get; set; }
}
public Record Model { get; set; } = new Record();
void MakeOption(RenderTreeBuilder __builder, string name)
{
<option value="@name">@name</option>
}
}
@marin-bratanov

Copy link
Copy Markdown

Third post- here's how I would do it - the method is to apply some logic that can now be pure and straightforward C#. If you don't need such complexity, do the text like the value - directly from the foreach.

<EditForm Model="@Model">

    <InputSelect class="form-control" @bind-Value="Model.Selection">
        @{
            string[] opts = new string[] { "John", "Jack", "Mark" };
            foreach (string item in opts)
            {
                <option value="@item">@GetComplexText(item)</option>
            }
        }
    </InputSelect>

    @Model.Selection

</EditForm>

@code {

    // https://stackoverflow.com/a/57840040/265706
    // https://visualstudiomagazine.com/articles/2019/10/02/blazor-gotchas.aspx

    public class Record
    {
        public string Selection { get; set; }
    }

    public Record Model { get; set; } = new Record();

    //that's how I'd get a more complex text or value for this if I needed it and it made the foreach unreadable
    string GetComplexText(string item)
    {
        return $"{item} {DateTime.Now.Ticks}";
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment