6


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.

7
  • What do you mean by "automatic new lines"?
    – Kevin
    Jan 16, 2014 at 12:41
  • New lines in the text or line breaks in the HTML? (they are different)
    – Tim
    Jan 16, 2014 at 12:41
  • I mean line breaks in the HTML, sorry for the diffuse question. Jan 16, 2014 at 12:44
  • 2
    Maybe wrap that in a <pre>...post content here... </pre>
    – rene
    Jan 16, 2014 at 12:45
  • How are newlines encoded in post_content?
    – Kevin
    Jan 16, 2014 at 12:45

2 Answers 2

3

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.

1
  • @PetterPettersson: No need to apologise. I was just a little concerned that you wanted some kind of automation in the Eval call rather than just adding another call on afterwards. If this worked for you though then we are all good. :)
    – Chris
    Jan 16, 2014 at 13:04
0

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") %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.