5
votes

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://docs.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?

3

3 Answers

6
votes

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 }' />
7
votes

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 })" />
0
votes

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