Why does Blazor assume a nullable component parameter is non-null?

Viewed 1569

How am I supposed to pass in a nullable value into a Blazor component? Currently I get an error during the build that complains my value cannot be null, but the component parameter is set as int?.

Component Base:

public class ProjectNameInputBase : ComponentBase
{
    private string[] _existingProjectNames = new string[0];
    private bool _loaded;

    [Parameter]
    public int? CompanyId { get; set; }

    [Parameter]
    public string ProjectName { get; set; }

    [Parameter]
    public EventCallback<string> ProjectNameChanged { get; set; }

    protected bool Disabled => _loaded;
    protected string[] Errors => 
        _existingProjectNames
            .Where(name => AreNamesEqual(name, ProjectName))
            .Select(name => $"Project with name \"{name}\" already exists in the company")
            .ToArray();

    protected async override Task OnParametersSetAsync()
    {
        if (CompanyId.HasValue)
        {
            _existingProjectNames = await FetchProjectNamesAsync(CompanyId.Value);
            _loaded = true;
        }
    }

    protected async Task HandleProjectNameChanged(ChangeEventArgs e)
    {
        if (ProjectNameChanged.HasDelegate)
        {
            await ProjectNameChanged.InvokeAsync(e.Value as string);
        }
    }

    private static bool AreNamesEqual(string a, string b) => a.Trim().ToLower() == b.Trim().ToLower();

    private async Task<string[]> FetchProjectNamesAsync(int companyId)
    {
        await Task.Delay(500);
        return new[] {
            "Project 1",
            "Project 2",
            "Project 3"
        };
    }
}

Component:

@inherits ProjectNameInputBase

<input type="text" value="@ProjectName" @onchange="@HandleProjectNameChanged" disabled="@Disabled" />
@foreach (var error in Errors)
{
    <small class="error">@error</small>
}

Consuming Component:

<label>
    Project Name
    <ProjectNameInput CompanyId="@Company?.Id" @bind-ProjectName="@ProjectName" />
</label>

Screenshot:

Nullable Error

3 Answers

No repro, using .net 5.

Either you are on an older version or you are missing (mis-spelling) @ProjectName or another element. Any other errors? The error you higlight could be collateral damage.

Could not reproduce on other machines. Seems to have been an issue with my instance of visual studio. The exact same code worked on another machine.

It's IDE's fault. Just close the Visual Studio. After you opened it again. It will be fine.

Related