我在 VS2015 的 cshtml Razor View 中遇到了一个奇怪的问题。我认为这一定是一个 Razor 错误,但如果可能的话,我将不胜感激进行健全性检查和解决方法的建议。
此问题是 @{}
代码块中的大括号未正确解析。我在 foreach
循环中有一个 if
语句,如果我使用大括号包围 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
}
有什么想法/建议吗?
最佳答案
从这一行中删除@:
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
}
关于c# - 在 VS2015 中使用 ASP.NET MVC Razor 时无法识别大括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40638662/