ASP.NET MVC Razor extra whitespace rendered
In Asp.net MVC, 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>
}
}
Is there any ways to remo开发者_开发知识库ve extra whitespace ?
I want to render a list this way: "1, 2, 3"
Quick and dirty:
@string.Join(", ", Enumerable.Range(1, 3))
Obviously a custom helper seems more appropriate to the job of formatting something in the view:
public static class HtmlExtensions
{
public static IHtmlString FormatList(this HtmlHelper html, IEnumerable<int> list)
{
return MvcHtmlString.Create(string.Join(", ", list));
}
}
and then simply:
@Html.FormatList(Model.MyList)
You are seeing the extra whitespace between the number and the comma because your razor template includes a line break (which displays as whitespace in the browser) between the number and the comma:
@for (int i = 1; i < 3; i++)
{
<text>@i</text> >LINE BREAK HERE<
if (i != 2)
{
<text>, </text>
}
}
I like Darin's answer, and I would suggest removing your loop and replacing it with a more declarative statement, but if you don't want to go that far, try at least removing the line break:
@for (int i = 1; i < 3; i++)
{
<text>@i</text>if (i != 2){<text>, </text>}
}
Instead of writing out bits of text in different places each time round the loop, you could accumulate all the text in a StringBuilder
, then outside the loop do @stringBuilderObject.ToString()
.
The problem is with the source that is generated. When you look at the actual source you get:
1 , 2 , 3
As you can see there is a lot of white space in there which browsers collapse down to a single space (look at the definition for normal).
Using a StringBuilder
or string.Join
is the way to fix this if all you're doing is outputting these three numbers. But if you're trying to do something else and this is a simplified example then see this blog post for a way of doing it using ol/ul
and li
s.
I might assume that it is not issue of Razor, but rather element is rendered with some margings.
- Open FireBug (or Chrome or whatever) and see that it is really markup issue.
- In you css file try to add
text { margin: 0 }
精彩评论