Why doesn't Visual Studio code formatting work properly for Razor markup?

Be sure to set the editor to use space characters and not tabs. The editor seems to completely lose its mind when tabs are used. This is a shame because all those space characters end up in the actual HTML output, greatly increasing the data transfer size. What I do is manually supplement the automatic formatting as I type. Not ideal, but hopefully Microsoft will have this figured out for the next service pack.


I found one "solution" that allows you to continue using tab indentation and have correct formatting. It's more of a pattern. The key is to use razor code blocks instead of inline code.

So for example, replace the following:

<div>
    <div>
        @if (true)
        {
            <b>Hi</b>
        }
    </div>
</div>

with:

<div>
    <div>
        @{
            if (true)
            {
                <b>Hi</b>
            }
        }
    </div>
</div>

The latter will format correctly, but the former won't.

Keep in mind, the formatting isn't perfect, but it's better than before.


It does not work correctly in all cases because it's a difficult problem to solve. Essentially you have 3 different editors (HTML, C#, and Razor) all interacting over the same text buffer. There are some cases (like this one) where the interactions have bugs. But we are working on improving the editor for the next release of Razor.