【发布时间】:2011-12-18 02:38:09
【问题描述】:
我在 Razor 视图中使用 if else 来检查 null 值,如下所示:
@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>
}
但是,无论我的模型金额为空还是有值,呈现的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>
【问题讨论】:
-
您必须向我们展示模型本身的外观,特别是 Model.Amount 字段。也许试试 @if (string.IsNullOrEmpty(item.Amount) 代替?
-
您好,感谢您的帮助,但金额是小数,如果我按照您在此处说明的操作,它不起作用。无论如何,请参考我的编辑,因为我决定在控制器中进行。谢谢你:)
-
If else 组合确实不适用于剃须刀。
标签: asp.net-mvc-3 razor if-statement