我在VS2012中创建了两个应用程序
现在我打开任何.cshtml文件并添加以下代码:
<div>
@if (true)
{
@string.Format("{0}", "test")
}
</div>
它在Application#1(mvc3)中工作正常,我看到“test”字显示。但它在Application#2(mvc4)中不起作用。
有人可以解释为什么会发生这种情况以及应该改变什么?
更新:我刚刚发现了一个非常奇怪的事情。如果用@ String.format(“some text”)替换@ string.format(“some text”),一切正常(注意大写字符串)
答案 0 :(得分:6)
我们在升级时遇到了类似的问题......看起来简单地写@string.Format("{0}", "test")
将不再像在MVC3中那样直接写入页面。你必须做这样的事情:
<div>
@if (true)
{
Html.Raw(string.Format("{0}", "test"));
}
</div>
或
<div>
@if (true)
{
<text>@string.Format("{0}", "test"))</text> //added @ to evaluate the expression instead of treating as string literal
}
</div>
答案 1 :(得分:0)
您使用的是Razor引擎吗?
由于您位于@if
区块,因此可以写下:string.Format("{0}", "test")
而不是@string.Format("{0}", "test")
。
请注意@
答案 2 :(得分:0)
在用于条件检查的Razor语法中,您可以使用一个@符号启动一个块,然后将您的条件放入...
E.g
@{var price=20;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
所以在你的情况下,你在一个区块内使用两个@。检查该部分,它将得到解决。
所以你的代码块应如下所示。
<div>
@if (Model == null)
{
<p>@string.Format("{0}", "test")</p>
}
</div>
最重要的是,如果你把“@”两次放在你的代码行中,它会给你提示如下图所示。这是Razor Syntax 4.0的功能。你也错过了“;”你的代码行。