Writing code in Blazor, the indentation is off
Asked Answered
E

2

8

When writing code in a Blazor (.razor) component, it formats it like this:

@code {
    void Abc()
        {

        }
}

Then I'll correct the indentation:

@code {
    void Abc()
    {

    }
}

but then whenever I insert an if condition, the indentation is messed up:

@code {
    void Abc()
    {
        if (true)
            {

            }
    }
 }

It's like it has an off-by-one indent problem. I don't know if it's me or Visual Studio. This is not a problem in a .cs file.

Electoral answered 3/4, 2021 at 11:31 Comment(7)
have you tried ctrl k + d ?Penknife
I am not sure if it's intended, but you are missing closing } for code blockRainband
@Rainband Sorry, I was just giving a snippet. The closing brace is there in the real code. It's a weird problem that I can't seem to find an answer to online, which makes me think it's my setup, but I can't figure out why.Electoral
@viveknuna Yes, but I don't want to reformat the whole doc, or a selection — because then I have to select it. May as well just fix it manually.Electoral
I've seen these problems occasionally. In Visual Studio Preview there is a new experimental razor editor that may do a better job. You can read about that here: devblogs.microsoft.com/aspnet/…Heinrick
I had the same problems some time ago (half a year ago). In my case those identation errors always appeared if I had an error or missing closing tag in the HTML part of the .razor file.Achieve
I’m voting to close this question because this was a problem with Visual Studio back in 2021 and not anymore now that the Razor editor is 100% compatible with Blazor. It's VERY unlikely this problem will occur again.Broadcaster
S
3

I tried ctrl k + d and the CodeMaid extension (they work perfectly on other Visual Studio project types) but are useless on Blazor project files.

I solved it with the "Code Alignment" extension.

Click on Extensions --> Manage Extensions --> Add "Code Alignment" by Chris McGrath.

The .razor .HTML and .css now have the proper indentation. Most importantly the dotted vertical lines between the and { } also re-appeared properly.

I have zero affiliation with the author of the extension.

Stonybroke answered 27/11, 2022 at 3:43 Comment(1)
How does "Code Alignment" work? What's it's shortcut keys?Degrease
M
0

I also use CodeMaid. In my computer, it doesn't work if I have 1 razor file with @code block.

but it does work when I use two seperate file (razor and .cs). This way CodeMaid indent all perfectly.

I wish I'll find a way for mono razor file. Code Aligmenent does do anything for me.

Mango answered 12/1 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.