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

Last updated by Matthew Parker [SSW] 7 months ago.See history

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: 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 />

ide warning
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>

build error
Figure: Good example - Build fails with an error

References

We open source. Powered by GitHub