ASP.NET MVC Razor extra whitespace rendered

大兔子大兔子 提交于 2019-12-14 03:46:01

问题


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 ?


回答1:


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)



回答2:


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>}
}



回答3:


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




回答4:


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 lis.




回答5:


I might assume that it is not issue of Razor, but rather element is rendered with some margings.

  1. Open FireBug (or Chrome or whatever) and see that it is really markup issue.
  2. In you css file try to add

text { margin: 0 }



来源:https://stackoverflow.com/questions/6652522/asp-net-mvc-razor-extra-whitespace-rendered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!