Petter Pettersson
Petter Pettersson

Reputation: 377

ASP.net C# New line


I need help with making a line break. I have this code:

<asp:Repeater runat="server" ID="rptPosts">
    <ItemTemplate>
        <h2><%#Server.HtmlEncode(Eval("post_title").ToString()) %></h2>
        <em><%#Server.HtmlEncode(Eval("post_posted").ToString()) %></em>
        <br />
        <%#Server.HtmlEncode(Eval("post_content").ToString()) %>
    </ItemTemplate>
</asp:Repeater>

I want to make post_content generate automatic new lines. I've tried with environment.newline but I can't seem to get it to work.

EDIT:
I mean to generate HTML breaks. Like nl2br() in PHP.

Upvotes: 6

Views: 11563

Answers (2)

Chris
Chris

Reputation: 27599

You need to do it after you have HTML encoded it. Otherwise any HTML you put in will end up getting encoded. So your best bet is:

Server.HtmlEncode(Eval("post_content").ToString())
    .Replace(Environment.NewLine, "<br>"+Environment.NewLine)

This will encode everything as normal and then everywhere it finds a new line it will replace it with a <br> tag (line break in HTML) and then the new line again (to make sure you keep the plain text line breaks as well as the HTML ones.

This isn't making "post_content generate automatic new lines" but I'm not too clear on what that means since post_content is just a key in whatever your data item is. If this is not adequate you'll have to clarify your requirements a bit more.

Upvotes: 3

Luaan
Luaan

Reputation: 63722

You can't, that's what Server.HtmlEncode protects you from. Your only option (if you can at all) is to remove the HtmlEncode and then just put <br/> in post_content - but that's open doors for hackers, of course.

The safest way and easiest way would be to do this:

<%#Server.HtmlEncode(Eval("post_content").ToString()).Replace("\r\n", "<br />\r\n") %>

Upvotes: 0

Related Questions