Asp.net-Mvc

如何在 razor 程式碼塊中插入空格?

  • May 25, 2020

VS2013,MVC5,剃刀,VB

我想要在“已回答”這個詞前面有空格。如何強制空格進入以下 Razor 程式碼塊?

@Code If Model.DisplayAnsweredFlag Then
 @If Model.Answered Then
   @Html.Raw("Answered")
  End If
End If
End Code

在 html.raw() 中,空格本身或前面文本中的空格似乎沒有被編碼到頁面中。但我也不能在程式碼塊中使用“ ”或“@ ”,因為它的語法不正確。

如果我使用糟糕的技術進行編碼,請提出建議,或者如果有其他方法可以輸入空格,請提出建議。

AndyBuk在這裡給出了答案:

https ://forums.asp.net/t/1772048.aspx?How+to+use+no+break+space+HTML+character+inside+if+brackets+in+a+view+

在那個連結中,他寫道:

Razor 語法介紹位於:

http ://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax 非常有用。
要強制為您的字元串輸出 html,您可以使用<text>阻止或@:作為前綴。

@if (condition)
{
   <text> </text>
   @: 
}

當我需要在表格中顯示結構時,我會使用這種方法。

item已經預先計算了屬性level

@helper PrintChild(List<ItemBalanceView> items)
{
   foreach (var item in items)
   {
       <tr>
           <td>@Html.Raw(InsertSpaces(item.LevelNum))<a class="text-primary" href='@Url.Content("~/Items/DetailsPos/")@item.ItemDocDetailID'>@item.ItemDocDetailName</a></td>
           <td>@Math.Round(item.Qty, 2)</td>
           <td>@Math.Round(item.Price, 2)</td>
           <td>@Math.Round(item.Total, 2)</td>
       </tr>

       if (item.Children != null)
       {
           @PrintChild(item.Children)
       }
   }
}

@functions  
{
   string InsertSpaces(int level)
   {
       var str = string.Empty;
       for (int i = 0; i < level; i++)
       {
           str += "  ";
       }

       return str;
   }
}

<table class="table table-sm">
   <thead>
       <tr>
           <th>Name</th>
           <th>Qty</th>
           <th>Price</th>
           <th>Total</th>
       </tr>
   </thead>
   <tbody>
       @foreach (var item in Model.BalancesAsStructure)
       {
           <tr>
               <td>@Html.Raw(InsertSpaces(item.LevelNum))<a class="text-primary" href='@Url.Content("~/Items/DetailsPos/")@item.ItemDocDetailID'>@item.ItemDocDetailName</a></td>
               <td>@Math.Round(item.Qty, 2)</td>
               <td>@Math.Round(item.Price, 2)</td>
               <td>@Math.Round(item.Total, 2)</td>
           </tr>

           if (item.Children != null)
           {
               @PrintChild(item.Children)
           }
       }
   </tbody>
   <tfoot>
       <tr style="background-color:#d7c0c0!important;">
           <th></th>
           <th></th>
           <th></th>
           <th>@Math.Round(Model.Total, 2)</th>
       </tr>
   </tfoot>
</table>

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