Blazor InputText: conditionally rendering an attribute

Aaron Hudon picture Aaron Hudon · Sep 20, 2019 · Viewed 7.5k times · Source

Blazor vRC1

I'm looking for a straightforward technique on how to conditionally render an attribute within an <InputText> (or any of the input components for that matter). This used to be simple in MVC Razor, where you'd just write the conditional logic within the @(...) statement. Now, writing @(...) has different meaning in the Razor syntax.

For example, I'd like to conditionally output the autofocus HTML attribute for InputText.

<InputText 
 @bind-Value="@TextProperty"
 @(MyModel.isAutoFocus ? "autofocus" : "") <-  This is invalid razor syntax!
/>

Answer

Aaron Hudon picture Aaron Hudon · Sep 20, 2019

As it turns out, Blazor will not render the attribute if the value of the attribute is false or null

https://docs.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.0#conditional-html-element-attributes

HTML element attributes are conditionally rendered based on the .NET value. If the value is false or null, the attribute isn't rendered. If the value is true, the attribute is rendered minimized.

<InputText @bind-Value="@TextProperty" autofocus="@MyModel.isAutoFocus" />