Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 882
Fabian Schmied Avatar asked Aug 28 '17 12:08

Fabian Schmied


People also ask

Which is the correct syntax of tag helper in form tag?

The syntax to register all the tag helpers that are in an assembly is to use asterisk comma (*,) and then the assembly name, Microsoft. AspNet. Mvc. TagHelpers.

What is the difference between HTML helper and tag helpers?

HtmlHelpers vs. Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior.

What are tag helpers in .NET Core explain built-in .NET core tag helpers briefly?

A Tag Helper Component is a Tag Helper that allows you to conditionally modify or add HTML elements from server-side code. This feature is available in ASP.NET Core 2.0 or later. ASP.NET Core includes two built-in Tag Helper Components: head and body . They're located in the Microsoft.


2 Answers

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 })" />
like image 96
Samuel Jack Avatar answered Nov 07 '22 13:11

Samuel Jack


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 }' />
like image 44
RonC Avatar answered Nov 07 '22 11:11

RonC