【问题标题】:Remove redundant spaces when render inside a <p> tag在 <p> 标签内渲染时删除多余的空格
【发布时间】:2017-06-05 14:32:03
【问题描述】:

我想渲染一个没有多余空格的段落。例如:

<p>There are cars, dogs, computers and houses!</p>

我写了以下代码:

var objects = new List<string> { "cars", "dogs", "computers", "houses" };

<p>
    There are
    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            @:and
        }
        else if (i > 0)
        {
            @:,
        }
        @objects[i]
    }
    !
<p>

@* This code will be rendered incorrectly by the browser like *@
<p>There are cars , dogs , computers and houses!</p>

如何删除&lt;p&gt; 标签内的空格?

【问题讨论】:

    标签: c# .net asp.net-mvc razor


    【解决方案1】:

    您可以使用string.Join(string, IEnumerable&lt;string&gt;) 将 n-1 个元素与 ", " 连接起来,然后使用 " 和 " 添加最后一个元素。

    <p>There are @string.Join(", ", objects.Take(objects.Count() - 1)) and @{objects.Last()}!</p>
    

    【讨论】:

      【解决方案2】:

      您可以使用这样的代码块在段落的外部或内部创建字符串。然后,把它扔到你的&lt;p&gt;&lt;/p&gt;

      外面

      @{
          var objects = new List<string> { "cars", "dogs", "computers", "houses" };
          string myObjs = "";
      
          for (var i = 0; i < objects.Count; ++i)
          {
              if (objects.Count > 1 && i == objects.Count - 1)
              {
                  myObjs += " and";
              }
              else if (i > 0)
              {
                  myObjs += ",";
              }
      
              myObjs += " " + objects[i];
          }
      }
      
      <p>There are @myObjs.Trim()!</p>
      

      内部

      <p>There are 
      @{
          var objects = new List<string> { "cars", "dogs", "computers", "houses" };
          string myObjs = "";
      
          for (var i = 0; i < objects.Count; ++i)
          {
              if (objects.Count > 1 && i == objects.Count - 1)
              {
                  myObjs += " and";
              }
              else if (i > 0)
              {
                  myObjs += ",";
              }
      
              myObjs += " " + objects[i];
          }
      }
      @myObjs.Trim()!</p>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-11
        • 2016-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-04
        • 1970-01-01
        相关资源
        最近更新 更多