Dave Miles
Dave Miles

Reputation: 11

Blazor/ dotnet 5.0.0: Set selected value in InputSelect

I need to set the selected value in the dropdown as a placeholder. Since the update to mcr.microsoft.com/dotnet/sdk:5.0 it will not work anymore. The input field is just empty and no value is selected. It was working before the update. Setting the selected attribute is not working too.

<InputSelect @bind-Value="someValue" id="someValue" required>
    <option value="">some Text</option>
    @foreach (var someValue in someValues)
    {
        <option value="@someValue">@someValue</option>
    }
</InputSelect>

Thank you for helping!

Upvotes: 1

Views: 2117

Answers (2)

Dark
Dark

Reputation: 181

You need to check that your someValue inside your Model allows to be nullable. Here you define

<option value="">...

that your option value is null or a empty string. If you use string as your datatype then everything is fine. But if you use an object like the newly added support for System.Guid then this has to allow for nullable values.

For example:

public Guid? someValue { get; set; } = null;

Using Guid.Empty would be also possible if you use this

<option value="@(System.Guid.Empty)">...

But that depends on your requirements.

Upvotes: 2

Brian Parker
Brian Parker

Reputation: 14553

The code you present works fine in rc2.

Note: I made assumptions about the EditForm usage.

<EditForm EditContext="SomeContext">

    <InputSelect @bind-Value="someValue" id="someValue" required>
        <option value="">some Text</option>
        @foreach (var someValue in someValues)
        {
        <option value="@someValue">@someValue</option>
        }
    </InputSelect>

</EditForm>

@someValue

@code {
    IEnumerable<string> someValues = new List<string> { "Value1", "Value2", "Value3" };
    EditContext SomeContext { get; set; }
    string someValue;

    SomeModel someModel = new SomeModel();
    protected override void OnInitialized()
    {
        SomeContext = new EditContext(someModel);
    }

    class SomeModel { }
}

However : You use "someValue" everywhere. I will need to see more of your code to find the error. If you paste this on the bottom of a junk/test projects index page this will work. The EditForm configuration/bindings maybe the issue.

Upvotes: 0

Related Questions