Search code examples
c#razorasp.net-coreasp.net-core-tag-helpers

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?


Solution

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