Search code examples
asp.net-mvcrazor

Razor escape colon inline


How do I escape colon in my razor code?

This is my issue:

@count@:: @item.Title - @item.Link - @item.Price

Which is causing an error after the @count variable. How am I able to use the colon next to my count?

It should render like this:

1: Title - Link - Price

** UPDATE **

My codeblock

@{
    int count = 0;
    foreach (var item in Model.Wishes) {
        count++;
        @count@:: @item.Title - @item.Link - @item.Price
        <br />
    }
}

Solution

  • You need to wrap your display part of the code in <text> tags. The colon does not need to be escaped.

    @{
        int count = 0;
    
        foreach (var item in Model.Wishes) {
            count++;
            <text>
            @count: @item.Title - @item.Link - @item.Price
            <br />
            </text>
        }
    }
    

    https://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax.aspx

    The <text> tag is an element that is treated specially by Razor. It causes Razor to interpret the inner contents of the <text> block as content, and to not render the containing <text> tag element (meaning only the inner contents of the <text> element will be rendered – the tag itself will not). This makes it convenient when you want to render multi-line content blocks that are not wrapped by an HTML element.

    https://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax#BM_CombiningTextMarkupAndCode

    Use the @: operator or the <text> element. The @: outputs a single line of content containing plain text or unmatched HTML tags; the <text> element encloses multiple lines to output. These options are useful when you don't want to render an HTML element as part of the output.