she*_*nyL 24 if-statement razor asp.net-mvc-3
我在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>
}
Run Code Online (Sandbox Code Playgroud)
但是,无论我的模型数量为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;
}
Run Code Online (Sandbox Code Playgroud)
并在View中调用:
<td class="shoptableamount">
@Html.Action("GetItemAmount", "Shop", new { fid = item.ShopListFoodID })
</td>
Run Code Online (Sandbox Code Playgroud)
Gab*_*oli 66
你必须使用 @()
@if (item.Amount == null)
{
@("--");
}
else
{
@String.Format("{0:0.##}", item.Amount)
}
Run Code Online (Sandbox Code Playgroud)
正如评论和其他答案中所述Html.Display
,不是用于显示字符串,而是用于显示来自ViewData
词典或来自的字符串Model
.阅读http://msdn.microsoft.com/en-us/library/ee310174%28v=VS.98%29.aspx#Y0
如果amount为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.Raw("--")
}
else
{
String.Format("{0:0.##}", item.Amount);
}
</td>
</tr>
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
84071 次 |
最近记录: |