Connor Low
Connor Low

Reputation: 7226

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.

Upvotes: 2

Views: 2015

Answers (2)

Connor Low
Connor Low

Reputation: 7226

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.

Upvotes: 3

JHBonarius
JHBonarius

Reputation: 11281

I just want to add another possibility You could add something like

@code{
    private const string placeholder = "@Handle";
}

And then

<InputText @bind-Value="@Inputs.Handle" placeholder="@placeholder" />

But this can quickly become very large and doesn't answer the question "How to escape @ in razor components". Maybe ask Microsoft?

Upvotes: 1

Related Questions