简体   繁体   English

如何删除换行符

[英]How to remove line breaks

I just do not get why the output does not show correctly 我只是不明白为什么输出无法正确显示

Here is my view code 这是我的查看代码

@model IEnumerable<TheSite.Post>
@{
    ViewBag.Title = "Index";
    Layout = null;
}
document.write('<table>

@foreach (var p in Model)
{
    <tr>
        <td>
            <a href="@p.Url">@p.Title</a>
        </td>
    </tr>
}

</table>');

Here is the output: 这是输出:

document.write('<table>

    <tr>
        <td>
            <a href="http://www.test.com">test</a>
        </td>
    </tr>

</table>');

Here is the output I need: 这是我需要的输出:

document.write('<table><tr><td><a href="http://www.test.com">test</a></td></tr></table>');

I tried using the stringbuilder but the output was escaped. 我尝试使用stringbuilder,但输出已转义。

The View Engine preserves line-breaks and spaces to create legible HTML. View Engine保留换行符和空格以创建清晰的HTML。

I don't see why you expect them to be removed automagically, but the simple idea would be not to insert them in the first place: 我不明白为什么希望自动删除它们,但是简单的想法是不要首先插入它们:

  document.write('<table> @foreach (var p in Model){<tr><td> ... }</table>');

Now this probably doesn't compile, just a basic idea. 现在,这可能不会编译,只是一个基本的想法。
It should compile. 它应该编译。 Just an ugly layout. 只是一个难看的布局。

Build it with the StringBuilder and use: 使用StringBuilder构建并使用:

@Html.Raw(builder.ToString())

Html.Raw on MSDN MSDN上的HTML.Raw

Henk has the right idea in the comments, just put into the string as you want it. Henk在注释中有正确的想法,只需将其放入字符串即可。

Barring that, you could try using Replace. 除非如此,否则您可以尝试使用“替换”。

document.write(mystring.Replace("\n","");

You can use the stringbuilder with @Html.Raw() to avoid escaping of html characters. 您可以将@Html.Raw()@Html.Raw()一起使用,以避免转义html字符。 You can append "\\" character on each of your html line to escape new lines in js, but I wouldn't recommend that. 您可以在每个html行上附加“ \\”字符,以在js中转义新行,但是我不建议这样做。 Instead I would use "+" 相反,我会使用“ +”

document.write('<table>' + 
 @foreach (var m in Model) {
   '<tr><td>@m</td></tr>'
 }
 + '</table>');

Or you could write a helper method which will return an instance of IHtmlString (something like return new HtmlString(yourStringBuilder.ToString()); 或者,您可以编写一个帮助程序方法,该方法将返回IHtmlString的实例(类似于return new HtmlString(yourStringBuilder.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM