Do you use the EditorRequired attribute for required parameters in Blazor?

Loading last updated info...

When you create a Blazor component, view parameters are marked with the [Parameter] attribute to indicate that they must be supplied by the parent component. By default, this is not enforced, which may lead to errors where you forget to pass in parameters where you use the component.

You should use the [EditorRequired] attribute to mark parameters that are required in your Blazor component.

TestComponent.razor

<h3>@Name</h3>
@code {
[Parameter]
public string? Name { get; set; }
}

Index.razor

@page "/"
<PageTitle>Home</PageTitle>
<TestComponent />

❌ Figure: Figure: Bad example - Developers could forget to pass a variable to the Name property

TestComponent.razor

<h3>@Name</h3>
@code {
[Parameter, EditorRequired]
public string? Name { get; set; }
}

Index.razor

@page "/"
<PageTitle>Home</PageTitle>
<TestComponent />
Image

✅ Figure: Good example - The IDE warns developers if they forget the Name parameter

You should configure this warning (RZ2012) as an error so your IDE will fail to build if you are missing a required parameter. Add <WarningsAsErrors>RZ2012</WarningsAsErrors> to your Blazor .csproj file:

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<WarningsAsErrors>RZ2012</WarningsAsErrors>
</PropertyGroup>
</Project>
Image

✅ Figure: Good example - Build fails with an error

References

Authors

Need help?

SSW Consulting has over 30 years of experience developing awesome software solutions.

We open source.Loving SSW Rules? Star us on GitHub. Star