Asp.net-Mvc

Razor 轉義冒號內聯

  • August 12, 2021

如何在剃刀程式碼中轉義冒號?

這是我的問題:

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

在 @count 變數之後導致錯誤。我如何使用計數旁邊的冒號?

它應該像這樣呈現:

1: Title - Link - Price

** 更新 **

我的程式碼塊

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

您需要將程式碼的顯示部分包裝在<text>標籤中。冒號不需要轉義。

@{
   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

<text>標籤是 Razor 特殊處理的元素。它導致 Razor 將<text>塊的內部內容解釋為內容,並且不渲染包含<text>標籤元素(這意味著只會渲染元素的內部內容<text>- 標籤本身不會)。當您想要呈現未由 HTML 元素包裝的多行內容塊時,這很方便。

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

使用@:運算符或<text>元素。輸出包含純文字或不匹配的 HTML 標記的@:單行內容;該<text>元素包含要輸出的多行。當您不想將 HTML 元素呈現為輸出的一部分時,這些選項很有用。

引用自:https://stackoverflow.com/questions/15994384