[英]string.Format not working in C# razor when inside if statement
我在剃刀视图中使用string.Format
来格式化来自viewModel的项。
当我像这样使用它时,它工作正常:
<td>
<b>@string.Format("{0:c}", item.TotalCreditPaid)</b>
</td>
但是,当我尝试在if语句中使用它时,它在视图中未显示任何内容:
<td>
<b>@if (item.AverageTimeToPay != null)
{
string.Format("{0} Days", item.AverageTimeToPay);
}
</b>
</td>
我逐步浏览了该项目,如果被击中, item.AverageTimeToPay
的值为12,但未显示任何内容。
知道为什么会这样吗? 谢谢!
您缺少@
和括号,请将其更改为此。
<td>
@if (item.AverageTimeToPay != null)
{
<b>@(string.Format("{0} Days", item.AverageTimeToPay))</b>
}
</td>
该代码正在运行,但没有向页面发出任何东西。
这将自动显示在页面上:
@string.Format("{0:c}", item.TotalCreditPaid)
因为Razor语法是如何工作的。 基本上,代码行的输出被发送到页面。 但是,这只是简单的代码:
string.Format("{0} Days", item.AverageTimeToPay);
就其本身而言,它什么也没做,它的输出需要完成一些工作。 在第二个示例中, if
块的输出被发送到页面,但是if
块不输出任何东西。 (这里的线索是分号。虽然很微妙,但这只是一种指示,它只是服务器端的一行代码,而不是Razor输出语句。)
您需要做的就是告诉它输出到页面:
<td>
@if (item.AverageTimeToPay != null)
{
<b>@string.Format("{0} Days", item.AverageTimeToPay)</b>
}
</td>
问题是您没有脱离代码块。
尝试以下方法:
<td>
@if (item.AverageTimeToPay != null)
{
<b>@string.Format("{0} Days", item.AverageTimeToPay)</b>
}
</td>
要么
<td>
<b>@if (item.AverageTimeToPay != null)
{
@:@string.Format("{0} Days", item.AverageTimeToPay);
}
</b>
</td>
您需要将字符串打印到页面上,所以请尝试:
<td>
<b>@if (item.AverageTimeToPay != null)
{
@string.Format("{0} Days", item.AverageTimeToPay);
}
</b>
</td>
您没有将输出呈现为Html字符串,可以通过两种方式实现
1)
<b>
@if (item.AverageTimeToPay != null)
{
@:@string.Format("{0} Days", item.AverageTimeToPay);
}
</b>
2)
@if (item.AverageTimeToPay != null)
{
<b>@string.Format("{0} Days", item.AverageTimeToPay)</b>
}
检查这个小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.