在<p>标记内进行渲染时删除多余空格

时间:2017-06-05 14:32:03

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

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

>composer clear-cache

我写了以下代码:

<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> 代码中的空格?

2 个答案:

答案 0 :(得分:2)

您可以使用string.Join(string, IEnumerable<string>)将&n-1元素加入&#34;,&#34;然后使用&#34;添加最后一个元素和&#34;。

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

答案 1 :(得分:1)

您可以使用类似的代码块在段落外部或内部创建字符串。然后,将其扔进<p></p>

<强>外

@{
    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>