79

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.

ProfK
  • 49,207
  • 121
  • 399
  • 775

11 Answers11

43

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.

Charles Burns
  • 10,310
  • 7
  • 64
  • 81
  • 29
    Highly annoying - I hate using spaces for indentation. It does work, though, so thank you for the suggestion. – Bobson Sep 22 '11 at 14:28
  • 13
    The spaces vs. tabs debate is hardly a closed one. It's a matter of preference. I prefer tabs, but not due to file size. There are arguments for both preferences, for example, http://lea.verou.me/2012/01/why-tabs-are-clearly-superior/ – Charles Burns Sep 10 '12 at 18:45
  • 2
    The fact that it ends up in HTML output does not actually increase data transfer size by much. Most web servers and browsers these days use compression, so repeated spaces doesn't really add that much. – Vincent McNabb Nov 25 '12 at 21:55
  • 1
    Seems that several versions have come out since your post and it's still a bug in Visual Studio 2012 Update 3 :( – NickG Jul 12 '13 at 08:27
  • 12
    Still a bug in Visual Studio 2015 :((( – Anshul Aug 31 '15 at 23:53
  • 3
    `greatly increasing the data transfer size` you've turned off server compression? Otherwise this is extremely nominal.... – Erik Philips Dec 16 '15 at 01:38
  • Has someone filled a bug to Microsoft? – Ignacio Soler Garcia Feb 27 '18 at 21:19
  • It's jacked up in 2017. – johnny Apr 26 '18 at 14:26
17

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.

Josh Mouch
  • 3,480
  • 1
  • 37
  • 34
8

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.

marcind
  • 52,944
  • 13
  • 125
  • 111
  • Yes, it is a difficult problem, and I am still very impressed by how Razor handles that mix, e.g. correctly scoping C# inverted commas inside HTML inverted commas etc. Nice work! – ProfK Aug 01 '11 at 20:02
  • 41
    I would like the option to not format my HTML/Razor at all. It's never seemed to work correctly and sometimes it reformats my HTML in ways that breaks the page (sometimes adding whitespace breaks the layout - grr). I suppose if all the bugs can be worked out and it produces clean html/razor I would be happy with that, but my guess is that this is too complicated and there will always be bugs. Also, it would be nice to use different formatting for Razor and C#. I typically put my braces on a separate line in C# but the same line in Razor. – Brian Aug 15 '11 at 21:01
  • 2
    It's been over a year and I'm still getting frustrated on a daily basis by the bugs. Is there anything scheduled for VS 2010, or is the focus on VS 2012 ? – user247702 Aug 28 '12 at 09:27
  • 1
    @Stijn a new version of MVC (including new Razor tooling) shipped recently (http://www.asp.net/mvc). However, you will have to upgrade your projects to use MVC 4. We do not currently have any plans to ship editor bug fixes for Razor in MVC 3. – marcind Aug 31 '12 at 22:53
  • 7
    @marcind I'm looking at a MVC 4 project in Visual Studio 2012 and it still does not work correctly if you use tabs instead of spaces (opening and closing bracket in ifs get spaces and not tabs). – Tor-Erik Sep 06 '12 at 11:48
  • @Ju9OR I'm sorry to hear that. Could you open a bug report with detailed repro steps in the Issue Tracker on http://aspnetwebstack.codeplex.com/ ? Thanks. – marcind Sep 07 '12 at 00:53
  • 1
    In this case, when you have tab indentation instead of spaces, the problem is that it inserts X spaces in front of the "@if" instead of X tabs. I don't see the difficulty in modifying the internal Visual Studio code that does this to look up the indentation character to use. The rest of the logic seems to already be there. – Josh Mouch Jan 17 '13 at 17:38
  • It's Dec 2014 and it's still a big problem. surely MS could have managed some improvement in three years and two version of Visual Studio... – Carl Onager Dec 16 '14 at 14:05
  • 2
    It's now worse in VS2015 update 2. If you switch all formatting options off and either paste code or type a new functionblock, all the code gets aligned left. Drives me nuts. What's so hard about "do nothing"? – Craig May 03 '16 at 23:09
6

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!

Derek Kalweit
  • 921
  • 6
  • 6
4

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”

Danny Law
  • 107
  • 1
  • 5
4

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

devowiec
  • 708
  • 6
  • 16
2

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>
Craig Poole
  • 740
  • 8
  • 19
0

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

Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206
0

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

FredyWenger
  • 2,236
  • 2
  • 32
  • 36
0

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

A Petrov
  • 417
  • 1
  • 9
  • 23
-2

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.

guest
  • 1
  • 1
    Not possible in VS2013 - format on paste cannot be disabled in cshtml files - tried everything... :o( – Miros Sep 17 '14 at 11:41