Razor inserts extra space between text blocks. I want to render a list this way: "1, 2, 3" but get "1 , 2 , 3".
@for (int i = 1; i < 3; i++)
{
<text>@i</text>
if (i != 2)
{
<text>, </text>
}
}
Are there any ways to remove this extra space?
Any of the following should work, depending on where your values actually come from:
You could use @Html.Raw. The code is more readable and the output doesn't have extra whitespace
Since this still a problem with the
<text>
tag in MVC 3 RTM + Tools Update and it can be a real headache to deal with, an alternative to eddiegroves' approach of removing whitespace from the code formatting is to avoid the use of the<text>
tag altogether.First, here is a rewrite of the original code that reproduces the problem and actually prints "1 , 2 , 3":
Here are four alternatives that print "1, 2, 3" instead of "1 , 2 , 3", but preserve code formatting by using @something instead of
<text>
.Solution #1: Using @("")
Solution #2: Using @var
Solution #3: Using @(expression)
Solution #4: Using @helpers
That last one is obviously overkill for the example, but might be a useful pattern for more complicated items and separators.
I would probably write a custom helper for this:
and then use it in my view:
I believe that there is an issue in the ASP.NET Razor RC that unfortunately will treat whitespace inside the "code context" as literal white space to write to the response.
The above example is "fixed" by removing the whitespace inside the code blocks:
Or more tidy:
By following this thread on the asp.net site there is a discussion which has a similar issue and Andrew Nurse responds
So if this is the same issue, hopefully it made the list to be fixed.