如何在剃刀代码块中插入空格?

时间:2015-02-02 17:13:18

标签: asp.net-mvc vb.net razor

VS2013,MVC5,Razor,VB

我想在“已回答”这个词前面加上空格。如何强制空格进入下面的Razor代码块?

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

在html.raw()中,空格本身或前面文本中的空格似乎没有被编码到页面中。但我也不能在代码块中使用“& nbsp”或“@& nbsp”,因为它的语法不正确。

如果我使用不良技术进行编码,请提供建议,或者如果有不同的方法来获取空格,请提供建议。

5 个答案:

答案 0 :(得分:13)

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>&nbsp;</text>
    @:&nbsp;
}

答案 1 :(得分:11)

解析HTML时会忽略空格,除非它们出现在pre块中。如果要填充一些文本,则需要采用以下方法之一:

  1. 将其包装在像pdiv这样的块级HTML元素中,然后使用CSS为元素添加填充/边距。这是推荐的方法。

  2. 使用&nbsp;代替您尝试填充的常规空格。渲染HTML时,只计算不间断的空格。但是,这种方法很糟糕,不推荐使用。

  3. 将文字换入pre元素。然后,将考虑<pre></pre>标记内的所有空格。但是,这种方法也很苛刻,不推荐使用。

答案 2 :(得分:4)

<text> &nbsp; &nbsp; &nbsp;</text>

插入&#34; &nbsp;&#34;添加更多空格。

答案 3 :(得分:1)

为什么不尝试不同的方法。使用带有一些填充的span标记

答案 4 :(得分:1)

当我需要在表中显示结构时,我使用这种方法。

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 += "&nbsp;&nbsp;";
        }

        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>