如果Razor中的其他声明不起作用

时间:2011-12-18 02:38:10

标签: asp.net-mvc-3 razor if-statement

我在Razor视图中使用if else来检查这样的空值:

 @foreach (var item in Model)
    {
        <tr id="@(item.ShopListID)">
            <td class="shoptablename">@Html.DisplayFor(modelItem => item.Name)
            </td>
            <td class="shoptableamount">
                @if (item.Amount == null)
                {
                    Html.Display("--");
                }
                else
                {
                    String.Format("{0:0.##}", item.Amount);
                }
            </td>
        </tr>

    }

但是,无论我的模型金额是null还是有值,渲染的html都不包含金额中的任何值。

我想知道为什么会这样。有什么想法吗?

...谢谢

编辑:

决定在控制器中做到这一点:

   // Function to return shop list food item amount
    public string GetItemAmount(int fid)
    {
        string output = "";

        // Select the item based on shoplistfoodid
        var shopListFood = dbEntities.SHOPLISTFOODs.Single(s => s.ShopListFoodID == fid);

        if (shopListFood.Amount == null)
        {
            output = "--";
        }
        else
        {
            output = String.Format("{0:0.##}", shopListFood.Amount);
        }
        return output;
    }

并在View中调用:

 <td class="shoptableamount">
                @Html.Action("GetItemAmount", "Shop", new { fid = item.ShopListFoodID })
            </td>

4 个答案:

答案 0 :(得分:65)

您必须使用@()

            @if (item.Amount == null)
            {
                @("--");
            }
            else
            {
                @String.Format("{0:0.##}", item.Amount)
            }

正如评论和其他答案中所述,Html.Display不是用于显示字符串,而是用于显示ViewData词典或Model中的数据。阅读http://msdn.microsoft.com/en-us/library/ee310174%28v=VS.98%29.aspx#Y0

答案 1 :(得分:6)

如果金额为空,我想你要显示“-----”。

@foreach (var item in Model)
    {
        <tr id="@(item.ShopListID)">
            <td class="shoptablename">@Html.DisplayFor(modelItem => item.Name)
            </td>
            <td class="shoptableamount">
                @if (item.Amount == null)
                {
                    @Html.Raw("--")
                }
                else
                {
                    String.Format("{0:0.##}", item.Amount);
                }
            </td>
        </tr>

    }

答案 2 :(得分:1)

那是因为您错误地使用了Display()方法。您使用的重载是Display(HtmlHelper, String)。如果您正在寻找“ - ”作为文本,您应该使用类似的东西:

@Html.Label("--");

答案 3 :(得分:1)

除了建议的@(&#34;&#34;)之外,实际上有两种方法可以在剃刀中显示来自代码块的文本,使用&lt; text&gt;标签和它的简写@:

    @{
        @("--")
        <text>--</text>
        @:--
    }

上面的代码会显示三次。