简体   繁体   中英

Curly Braces not recognised when using ASP.NET MVC Razor in VS2015

I've hit a strange problem in VS2015 in a cshtml Razor view. I think it must be a Razor bug, but would appreciate a sanity check and suggestions for a workaround if poss.

This issue is that curly braces within a @{} code block are not resolving properly. I have an if statement within a foreach loop and if I use curly braces to surround the if action, I get a compilation error. Interestingly enough, curly braces after the else statement seem fine.

This would be easier to demonstrate with VS colour coding, but here goes.

This works:

@{
    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

However, if I now add curly braces around the if action, it won't compile:

@{
    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 
} 

Any thoughts/suggestions?

Remove the @ from this line:

var type = @t.Item3.PropertyType;

You're already in a C# code area, so you don't need the @ to reference variables as you would if you were in a HTML area.

It's okay to do that on the line below, because when you start a line with recognised HTML it assumes a switch back to HTML, and breaks out of C#. So you're effectively in a HTML section there.

<p>@t.Item1 @t.Item2 @t.Item3.PropertyType</p>

Just as an aside, I often end us using this shortcut, when I want to force HTML mode so I can output the value of a variable.

@if (t.isExample)
{
   @: @t.OutputThis
}

when you use @ token on razor views, you are telling the engine to stop parsing html, and try to interpret the C# language, razor is clever enough to know when to stop the parsing because the token you are trying to write is part of the html language, so you need to specify at which point razor should read your C# code, thats why on your if statement you need to turn on the recognition again with the @ token. If you want to escape the @ token, because you are trying to write @ as html, then use @@ instead. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM