Search code examples
.netrazorblazorblazor-server-side

How do I Escape @ in Blazor Component HTML Attributes?


I want to use <InputText /> to render the following:

<input placeholder="@Handle" class="valid">

Here is what I tried:

<InputText @bind-Value="Handle" placeholder="Handle" />    @* <- Compiles, but not what I want. *@
<InputText @bind-Value="Handle" placeholder="@@Handle" />  @* <- Fails. *@

But I get the following error:

RAZORGENERATE : error RZ9986: Component attributes do not support complex content (mixed C# and markup). 
Attribute: 'placeholder', text: '"@"Handle'

So using @@ is technically still razor code (an escaped '@') and can't be used with an attribute. How can I put render an '@' in an HTML attribute?

I am using .NET 5.0, server-side Blazor.


Solution

  • HTML Solution

    Immediately realized I could just use HTML character codes. This works:

    <InputText @bind-Value="@Inputs.Handle" placeholder="&#64;Handle" />
    

    Razor Solution

    Or, I could just use razor and do this:

    <InputText @bind-Value="@Inputs.Handle" placeholder="@($"@{UserHandle}")" />
    

    The moral is, you can't combine razor with raw HTML in component attributes (and know that @@ is still razor syntax). Pick one and it will work.