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

标签 c# asp.net-mvc razor

我在 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/

相关文章:

asp.net-mvc - 添加 View 对话框 MVC3

asp.net-mvc - WriteAttributeTo 方法中的空引用异常

jquery - 使用部分 View 的客户端验证

c# - 如何在 mvc4 Razor 中为列表框选择复选框

asp.net - 使用 SQL Server 将信号发送者用户映射到连接

c# - 在 View 中显示两个模型?

c# - 使用套接字将数据从C#应用程序发送到Lua应用程序

c# - mvc DisplayName 或 Display(Name=...) 取决于另一个模型属性

c# - 仅从特定网站重定向

c# - 使用循环使用对象列表中的项目填充数组