How to add new lines inside P tag from server side by passing message p.InnerText

2.2k views Asked by At

I am using a p tag with id p1.

<p id="p1" runat="server" ></p>

I have a message which I am passing from server side which is stored in variable "message".

This is first line
This is second line

I am passing this value to the p tag by

p1.InnerText=message.

My question is, How to add new line in the p tag from server side as shown above? I have tried
but it is not working :

"This is firstline"+"<br/>"+"This is second line"
4

There are 4 answers

0
user1429080 On

If you want new lines in the original string to be shown in the paragraph, you must use the InnerHtml property and add <br /> tags instead of newline chars/strings. But that means you need to take care of html encoding the strings yourself. Something like this would work:

void Function1(string value)
{
    var messageRows = value.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
    StringBuilder builder = new StringBuilder();
    foreach (string oneRow in messageRows)
    {
        builder.Append(Server.HtmlEncode(oneRow) + "<br />");
    }
    p1.InnerHtml = builder.ToString();
}

Test it:

protected void Page_Load(object sender, EventArgs e)
{
    string text_with_newlines = "part 1" + Environment.NewLine + "part 2" + Environment.NewLine + "part <script type=\"javascript\">alert('boo!');</script>";
    Function1(text_with_newlines);
}
0
Sandeep Raj Shakya On

Use as raw string:

string string = String.Format(@"This is firstline. {0}This is second line.", Environment.NewLine);

It works.

4
Anand Systematix On

You can use Environment.NewLine between strings.

For example

"This is firstline" + Environment.NewLine + "This is second line"

Update 1:

You can use it like :-

Function1("This is firstline" + Environment.NewLine + "This is second line");

Public void Function1(string value)
{ 

  p1.InnerText=value

}

If it not work than please try :-

p1.InnerHtml = newLine

Update 2:

With <pre> you need to use "\n" instead of Environment.NewLine

<pre id="test" runat="server"></pre>

test.InnerText = newLine;
5
Bhasin On

Use :

p1.InnerHtml = "This is firstline"+"<br/>"+"This is second line";

It will work