Fabian Schmied
Fabian Schmied

Reputation: 4154

String literals in ASP.NET Core MVC tag helper arguments

Razor allows arguments to ASP.NET Core MVC tag helpers to be written as inline C# expressions within the corresponding attribute declaration. However, since HTML attributes are delimited by quotation marks, what's the syntax if such an expression should itself contain a quotation mark?

Here's a sample from https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring:

<website-information info="new WebsiteContext {
    Version = new Version(1, 3),
    CopyrightYear = 1638,
    Approved = true,
    TagsToShow = 131 }" />

What would this look like if one of the WebsiteContext properties were to take a string literal?

Upvotes: 5

Views: 2515

Answers (3)

Samuel Jack
Samuel Jack

Reputation: 33270

If you wrap the new expression in @(...) it will all be treated as C# code so you won't have a problem.

Like this:

<website-information info="@(new WebsiteContext {
                            Version = new Version(1, 3),
                            CopyrightYear = "1638",
                            Approved = true,
                            TagsToShow = 131 })" />

Upvotes: 7

Fabian Schmied
Fabian Schmied

Reputation: 4154

As an alternative workaround to the one described in Ron C's answer, one could also put the WebSiteContext construction code into a separate Razor code block, storing the result in a variable.

@{
var context = new WebsiteContext {
        Version = new Version(1, 3),
        CopyrightYear = "1638",
        Approved = true,
        TagsToShow = 131 };
}

<website-information info="@context" />

Upvotes: 0

RonC
RonC

Reputation: 33851

Since my original answers was flawed, here is an approach that will work that I tested on code similar to yours:

If the CopyrightYear is a string what you can do is use single quotes for the outer quotes and use double quotes for the strings like so:

 <website-information info='new WebsiteContext {
                                Version = new Version(1, 3),
                                CopyrightYear = "1638",
                                Approved = true,
                                TagsToShow = 131 }' />

Upvotes: 6

Related Questions