Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make component parameter required when building a custom Blazor component?

Tags:

c#

blazor

When I try to build a Blazor component I can define parameters for it like this:

@code {

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

}

My question is can I make this parameter required so that, when component is used, the project will not build unless I provide the specified parameter? Is this something I should even be worried about? I suppose I could handle any invalid values in component initialization by maybe throwing an exception if the value is not provided like this:

protected override void OnInitialized()
{
    base.OnInitialized();
    if (string.IsNullOrWhiteSpace(MyString)) {
       // throw an exception here...
    }
}

but is that the right way to handle this?

like image 674
Marko Avatar asked Jun 01 '20 23:06

Marko


Video Answer


4 Answers

.NET 6 and newer

This can be accomplished with the [EditorRequired] attribute. Example:

[Parameter, EditorRequired]
public string Name { get; set; }

This will give an IDE warning to consumers of components that parameters are missing if their parameters are not supplied.

Before .NET 6

Currently, you’ll have to do exactly as you said.

like image 78
Ben Sampica Avatar answered Oct 23 '22 09:10

Ben Sampica


As @BenSampica said, gotta wait until .NET 6 for this, but you can use

[Parameter]
public string MyString { get; set; } = null!;

for now. Won't generate compiler error, but won't let you use it either.

like image 20
thalacker Avatar answered Oct 23 '22 09:10

thalacker


Not yet, no. The best you can do at the moment is to throw an exception in SetParametersAsync.

There's a section on optional route parameters on Blazor University that will show how to check if a parameter was passed or not. You simply make it nullable and check it isn't null. https://blazor-university.com/routing/optional-route-parameters/

Alternatively, if override SetParametersAsync you are passed a ParameterView parameters parameter, you can use parameters.TryGetValue to determine if a parameter was passed, and throw an exception if it wasn't.

But there is currently no way to cause compile-time errors.

like image 2
Peter Morris Avatar answered Oct 23 '22 10:10

Peter Morris


I like to combine [EditorRequired] with an initial value of null!.

[Parameter, EditorRequired]
public string MyString { get; set; } = null!;

Technically, the value will be null before OnInitialized() runs, such as in the constructor. Still, it's more convenient than having to treat it as possibly null everywhere else.

like image 1
mfluehr Avatar answered Oct 23 '22 10:10

mfluehr