在 VS2015 中使用 ASP.NET MVC Razor 时无法识别大括号

Shh*_*Tot 1 c# asp.net-mvc razor

我在 VS2015 的 cshtml Razor 视图中遇到了一个奇怪的问题。我认为这一定是 Razor 错误,但如果可能的话,希望进行健全性检查并提供解决方法的建议。

此问题是@{}代码块内的花括号无法正确解析。我在循环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
Run Code Online (Sandbox Code Playgroud)

但是,如果我现在在 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 
} 
Run Code Online (Sandbox Code Playgroud)

有什么想法/建议吗?

小智 5

从这一行中删除@:

var type = @t.Item3.PropertyType;
Run Code Online (Sandbox Code Playgroud)

您已经位于 C# 代码区域中,因此不需要像在 HTML 区域中那样使用 @ 来引用变量。

可以在下面的行中执行此操作,因为当您以可识别的 HTML 开始一行时,它会假定切换回 HTML,并脱离 C#。所以您实际上处于 HTML 部分。

<p>@t.Item1 @t.Item2 @t.Item3.PropertyType</p>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,当我想强制使用 HTML 模式以便输出变量的值时,我经常使用这个快捷方式。

@if (t.isExample)
{
   @: @t.OutputThis
}
Run Code Online (Sandbox Code Playgroud)