Search code examples
asp.net-corevisual-studio-coderazor-pagesfolding

How to enable code folding in ASP.NET Core Razor syntax in VS Code?


I am trying to edit Razor pages (.cshtml) in VS Code for a .NET Core project. When I open the file it chooses the ASP.NET Razor (aspnetcorerazor) language mode. It does syntax highlighting perfectly, but there's one important feature missing.

When I hover near the page number I cannot see the folding controls for code folding. So, there is no way to fold the code.

When I change my language mode back to HTML, I get the code folding back, but then I lose all the syntax highlighting of Razor syntax.

Has anybody experienced the same issue? Currently, as a workaround I have to switch back and forth between the HTML and ASP.NET Core Razor language modes for code folding.


Solution

  • You may use the VSCode Extension Better Folding for that.

    To configure for cshtm/razor files only, just put these lines to your .vscode/settings.json:

    "[aspnetcorerazor]": {
            "explicitFolding.rules": [
                {
                    "begin": "{/*",
                    "end": "*/}"
                },
                {
                    "indentation": true,
                    "offSide": true
                }
            ]
        }
    

    That will add the abillity to fold the code by indention and by curly brackets.

    offSide (default: false) decide whether empty lines belong to the previous or the next block. Used by the default indentation provider and defined by language’s configuration (not accessible by an extension).

    Of course you can config that for the whole project folder by removing the language selector:

    "explicitFolding.rules": [
        {
            "begin": "{/*",
            "end": "*/}"
        },
        {
            "indentation": true,
            "offSide": true
        }
    ]