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

asp.net MvcVisual StudioVisual Studio-2010asp.net Mvc-3Razor

asp.net Mvc Problem Overview


Or, should I rather ask, when will VS code formatting work properly for Razor markup? The formatting works for most structures, but it seems to choke on 'if' blocks. The code below is as it is formatted by VS. It is very easy to fix this case, with one more indent, but I nicely accepted the formatting in everyday use, and like to use it often for the bulk of my code, so I'd rather avoid manual formatting if possible. Right now I just leave it as VS formats it.

@{ 
    if (User.Identity.IsAuthenticated)
    {
    <text>Hello </text>
    @Html.Display("@ViewBag.UserName") <text> - </text>
    @Html.ActionLink("Sign Out", "LogOff", "Account", null, new { style = "font-weight: bold;" })
    }
 }

I think it's important for readability that, e.g. in the above, the body of the if block is indented, besides just looking nicer.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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.

Solution 2 - asp.net Mvc

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.

Solution 3 - asp.net Mvc

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.

Solution 4 - asp.net Mvc

A better alternative here(rather than using spaces for tabs), is to change the block indenting for HTML and C#/VB to "Block" instead of "Smart". This isn't a full solution, but IMO is a far less painful work-around than using spaces!

Solution 5 - asp.net Mvc

In my case it was resharper overriding formatting options.

If your using reshaper and getting this issue try this...

Resharper >> Options >> Razor >> Editor & Formatting >> Untick “Auto-format on enter”

Solution 6 - asp.net Mvc

I found another solution for this. Just select all code in file, click Shift + tab to remove all tabs before code, copy and paste it. Visual studio automatically format code. Work on VS 2013 .cshtml file

Solution 7 - asp.net Mvc

I know it's not really the answer you're looking for but I've used WriteLiteral to get around my formatting issues.

For example, when I write:

<div>
    @foreach (var item in Model) {    
        if (condition) {
            @:</div><div>
        }
        <a href="@item.Url">@item.Label</a>
    }
</div>

Visual Studio tries to change it to:

<div>
    @foreach (var item in Model) {    
        if (condition) {
            @:
        </div><div>
        }
        <a href="@item.Url">@item.Label</a>
    }
</div>

Which causes the page to throw an error.

If you use WriteLiteral you can fool the formatter into ignoring the line but it ain't pretty:

<div>
    @foreach (var item in Model) {    
        if (condition) {
            WriteLiteral("</div><div>");
        }
        <a href="@item.Url">@item.Label</a>
    }
</div>

Solution 8 - asp.net Mvc

Right now I'm on VS2013 ASP.NET MVC 5 and I still have that problem. What I found to be a lot helpful is to put the first expression on the same line where the opening block symbol is (@{). That way razor code formatting produces a far better result. Here are the before and after cases:

BEFORE

BEFORE

AFTER

enter image description here

Solution 9 - asp.net Mvc

I work with VS2017 15.9.2 and still have the problem.
After change the editor settings to use spaces instead of tabs, the behavior in editing (e.g. copy - paste code lines) is way better, but "Format Document" still add wrong indents by every call.

No solution, but a short update:

It seems as the issue is solved partial in Visual Studio 2019 version 16.0 Preview 2.1
Link to MS for the issue

Further short update:
I have found a (bad and ugly) workaround (to write the whole code to a razor control in ONE line. You can find the details here Workaround to wrong indentation Razor Controls

Solution 10 - asp.net Mvc

You might want to try Improvements to the new Razor editor in Visual Studio - it has greatly improved the formatting quality (still imperfect, though).

Solution 11 - asp.net Mvc

I recommend you prevent automatic formatting to trigger by commenting the piece of code where you paste. This way things don't get broken on paste.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionProfKView Question on Stackoverflow
Solution 1 - asp.net MvcCharles BurnsView Answer on Stackoverflow
Solution 2 - asp.net MvcJosh MouchView Answer on Stackoverflow
Solution 3 - asp.net MvcmarcindView Answer on Stackoverflow
Solution 4 - asp.net MvcDerek KalweitView Answer on Stackoverflow
Solution 5 - asp.net MvcDanny LawView Answer on Stackoverflow
Solution 6 - asp.net MvcdevowiecView Answer on Stackoverflow
Solution 7 - asp.net MvcCraig PooleView Answer on Stackoverflow
Solution 8 - asp.net MvcMikayil AbdullayevView Answer on Stackoverflow
Solution 9 - asp.net MvcFredyWengerView Answer on Stackoverflow
Solution 10 - asp.net MvcA PetrovView Answer on Stackoverflow
Solution 11 - asp.net MvcguestView Answer on Stackoverflow