Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 remove extra whitespace ?

like image 445
Ghooti Farangi Avatar asked Jul 11 '11 15:07

Ghooti Farangi


3 Answers

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)
like image 116
Darin Dimitrov Avatar answered Oct 14 '22 10:10

Darin Dimitrov


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>}
}
like image 39
Eric King Avatar answered Oct 14 '22 10:10

Eric King


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().

like image 1
Graham Clark Avatar answered Oct 14 '22 12:10

Graham Clark