aventic
aventic

Reputation: 1514

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

Upvotes: 11

Views: 5047

Answers (2)

Jasen
Jasen

Reputation: 14250

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.

Upvotes: 19

Walt Ritscher
Walt Ritscher

Reputation: 7037

If count is declared as a variable, then this should work.

@{
   var count = 4;
}

   @count: 

If count is part of your model, then this should work.

@model MvcApplication4.Models.DemoViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>



@Model.Count: 

Upvotes: 0

Related Questions