asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了asp.net-mvc-3 – 如果在Razor中的else语句不起作用大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在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

大佬总结

以上是大佬教程为你收集整理的asp.net-mvc-3 – 如果在Razor中的else语句不起作用全部内容,希望文章能够帮你解决asp.net-mvc-3 – 如果在Razor中的else语句不起作用所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: