如果剃刀else语句不工作 [英] if else statement in Razor is not functioning
问题描述
我使用的是其他人,如果在的Razor视图来检查这样的空值:
@foreach(以型号VAR项)
{
&所述; TR的id =@(item.ShopListID)>
< TD类=shoptablename> @ Html.DisplayFor(modelItem => item.Name)
< / TD>
< TD类=shoptableamount>
@if(item.Amount == NULL)
{
Html.Display( - );
}
其他
{
的String.Format({0:0 ##},item.Amount);
}
< / TD>
< / TR> }
不过,不管我的模型数量为空或有一个值,呈现不包含在任何金额值的HTML。
我不知道为什么会这样。任何想法?
谢谢...
编辑:
于是决定做它的控制器:
//函数返回店铺名单的食品项目金额
公共字符串GetItemAmount(INT FID)
{
字符串输出=; //基于shoplistfoodid选择项目
VAR shopListFood = dbEntities.SHOPLISTFOODs.Single(S = GT; s.ShopListFoodID == FID); 如果(shopListFood.Amount == NULL)
{
输出= - ;
}
其他
{
输出=的String.Format({0:0 ##},shopListFood.Amount);
}
返回输出;
}
在查看调用,如:
< TD类=shoptableamount>
@ Html.Action(GetItemAmount,店,新的{FID = item.ShopListFoodID})
< / TD>
您必须使用 @()
@if(item.Amount == NULL)
{
@( - );
}
其他
{
@的String.Format({0:0} ##,item.Amount)
}
作为评价和其他的答案中, Html.Display
不是显示字符串,而是从的ViewData 显示数据指出code>词典或从
模式
。阅读 http://msdn.microsoft。 COM / EN-US /库/ ee310174%28V = VS.98%29.aspx#Y0
I am using an if else in Razor view to check for null value like this:
@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>
}
However, no matter my model amount is null or having a value, the html rendered do not contain any value in the amount.
I wonder why this is happening. Any idea?
Thanks...
EDIT:
Decided to did it in controller:
// 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;
}
and call at View like:
<td class="shoptableamount">
@Html.Action("GetItemAmount", "Shop", new { fid = item.ShopListFoodID })
</td>
You have to use the @()
@if (item.Amount == null)
{
@("--");
}
else
{
@String.Format("{0:0.##}", item.Amount)
}
As noted in the comments and other answers, the Html.Display
is not for displaying strings, but for displaying data from the ViewData
Dictionary or from a Model
. Read http://msdn.microsoft.com/en-us/library/ee310174%28v=VS.98%29.aspx#Y0
这篇关于如果剃刀else语句不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!