【问题标题】:Curly Braces not recognised when using ASP.NET MVC Razor in VS2015在 VS2015 中使用 ASP.NET MVC Razor 时无法识别大括号
【发布时间】:2016-11-16 17:36:45
【问题描述】:

我在 VS2015 的 cshtml Razor 视图中遇到了一个奇怪的问题。我认为这一定是 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 
} 

有什么想法/建议吗?

【问题讨论】:

    标签: c# asp.net-mvc razor


    【解决方案1】:

    从这一行删除@:

    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
    }
    

    【讨论】:

      【解决方案2】:

      当您在 razor 视图上使用 @token 时,您是在告诉引擎停止解析 html,并尝试解释 C# 语言,razor 足够聪明,知道何时停止解析,因为您尝试编写的 token 是html 语言的一部分,因此您需要指定 razor 应该在什么时候读取您的 C# 代码,这就是为什么在您的 if 语句中您需要使用 @ 标记再次打开识别。如果您想转义 @ 标记,因为您正在尝试将 @ 编写为 html,请改用 @@。希望这会有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 2017-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多