Search code examples
asp.net-coreblazorblazor-server-side

Blazor InputText: conditionally rendering an attribute


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

Solution

  • You could try below code:

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

    Refer to https://github.com/aspnet/AspNetCore/issues/10122