5

Closed

Razor outputs blank lines

description

Create a controller and a razor view. In controller, set Response.ContentType = "text/xml".
In view, put
@{
Layout = null;
}
<?xml version="1.0" encoding="utf-8" ?>

Now run the view. No matter what you do the <?xml block will be on the 2nd line output, which of course is an invalid xml document.

Enter webforms pages. Create a view containing this all on first line in view:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" ContentType="text/xml" %><?xml version="1.0" encoding="utf-8" ?>

Webforms works and does not output extra lines - Razor does. Appears there is blank at the top and everytime there is @{} block. Here is another user reporting. http://stackoverflow.com/questions/11327787/empty-first-line-in-razor-mvc-4-rc
Closed Apr 19, 2013 at 6:47 PM by yishaigalatzer
Thanks again for reporting this bug.
We spent some time digging into this, and we believe that removing the whitespace was the right thing to do, fixing it today will be a potential breaking change for any application relying (inadvertently or not) on the spacing Razor currently injects into the document.

comments

eilonlipton wrote Apr 16, 2013 at 12:07 AM

Thank you for reporting this bug. For now we recommend placing the XML declaration above the @{} code block. This will cause Razor to render that line first.

Untit1ed wrote Sep 25, 2013 at 1:22 AM

It makes no sense, razor code block shouldn't generate a whitespace. Why it's not fixed yet?

Untit1ed wrote Oct 5, 2013 at 2:34 AM

XML declaration on html page? That's not even a workaround.

eilonlipton wrote Oct 7, 2013 at 9:28 PM

Adding an XML declaration to the HTML page is not a workaround - that's just the scenario originally described in the bug.

There's another easy workaround for this issue: Place the tag (an XML declaration in this case) on the same line as the "}" that closes the @{ } Razor code block:
@{
    Layout = null;
}<?xml version="1.0" encoding="utf-8" ?>
We evaluated the risk of applying a fix and we feel that due to this scenario not being very common and due to the workarounds being relatively simple, it is not worth fixing the bug.