简体   繁体   中英

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.

The View Engine preserves line-breaks and spaces to create legible 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:

@Html.Raw(builder.ToString())

Html.Raw on MSDN

Henk has the right idea in the comments, just put into the string as you want it.

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. You can append "\\" character on each of your html line to escape new lines in js, but I wouldn't recommend that. 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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