我在一个cshtml Razor视图中遇到了VS2015中的一个奇怪问题。我认为它一定是一个剃刀错误,但如果可能的话,我会非常感谢一个完整性检查和解决方法的建议。
此问题是@{}
代码块中的花括号无法正确解析。我在if
循环中有一个foreach
语句,如果我使用花括号来包围if
操作,我会收到编译错误。有趣的是,else
语句之后的花括号似乎很好。
使用VS颜色编码可以更容易地进行演示,但是这里有。
这有效:
@{
var nestLevel = 0;
foreach (var t in xmlHelper.GetProperties(asm, ViewBag.xmlType, "root"))
{
var type = @t.Item3.PropertyType;
if (xmlHelper.builtInTypes.Contains(type.ToString()))
<p>@t.Item1 @t.Item2 @t.Item3.PropertyType</p>
else
{
nestLevel++;
}
}
} //VS shows the @{} code block ending here as expected
但是,如果我现在在if动作周围添加花括号,它就不会编译:
@{
var nestLevel = 0;
foreach (var t in xmlHelper.GetProperties(asm, ViewBag.xmlType, "root"))
{
var type = @t.Item3.PropertyType;
if (xmlHelper.builtInTypes.Contains(type.ToString()))
{
<p>@t.Item1 @t.Item2 @t.Item3.PropertyType</p>
}
else
{
nestLevel++;
}
} //VS now incorrectly shows the @{} code block ending here
}
有任何想法/建议吗?
答案 0 :(得分:3)
从此行中删除@:
var type = @t.Item3.PropertyType;
您已经在C#代码区域,因此您不需要@引用变量,就像您在HTML区域中一样。
可以在下面的行中执行此操作,因为当您使用已识别的HTML启动一行时,它会假定切换回HTML,并突破C#。所以你在那里有效地使用HTML部分。
<p>@t.Item1 @t.Item2 @t.Item3.PropertyType</p>
顺便说一下,当我想强制使用HTML模式以便输出变量的值时,我经常会结束使用这个快捷方式。
@if (t.isExample)
{
@: @t.OutputThis
}
答案 1 :(得分:0)
当您在razor视图上使用@doken时,您告诉引擎停止解析html,并尝试解释C#语言,razor非常聪明,知道何时停止解析,因为您尝试编写的令牌是html语言的一部分,所以你需要指定razor应该在哪个位置读取你的C#代码,这就是为什么你的if语句需要再次使用@ token打开识别。如果你想要转义@标记,因为你试图将@编写为html,那么请使用@@代替。希望这有帮助