加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 如果在Razor中的else语句不起作用

发布时间:2020-12-16 00:43:16 所属栏目:asp.Net 来源:网络整理
导读:我在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(
我在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;
    }

并在视图中调用如下:

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

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读