I came up with a way to retain white space and still allow html to be displayed instead of being rendered as html formatting in the comments section.
My C# is more than a bit rusty so bare with me on this one.
The idea is to convert the line breaks the user entered into some character sequence the user is not likely to enter as a comment. Then after the HtmlEncode method has been called, we will convert this special character sequence into an HTML <br> tag. This will allow the user to enter any HTML they wish as a comment, including <br>, and it will be displayed as text and not rendered by the browser.
The code looks something like this:
//First we have to change the AddComment function so it saves our special character sequence instead of the line break the user entered.
void AddComment(Object s, EventArgs e)
{
if (Page.IsValid)
{
IssueComment comment = new IssueComment(IssueId, txtComment.Text.Trim().Replace(System.Environment.NewLine, "<!br!>"), Page.User.Identity.Name);
comment.Save();
txtComment.Text = String.Empty;
BindComments();
}
}
//Now we have to change the display function so it will convert our special character sequence to the HTML <br> tag but we need to wait until after the HtmlEncode method has been called.
void grdCommentsItemDataBound(Object s, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
IssueComment currentComment = (IssueComment)e.Item.DataItem;
Label lblCreatorDisplayName = (Label)e.Item.FindControl( "lblCreatorDisplayName" );
lblCreatorDisplayName.Text = currentComment.CreatorDisplayName;
Label lblDateCreated = (Label)e.Item.FindControl( "lblDateCreated" );
lblDateCreated.Text = currentComment.DateCreated.ToString("f");
Literal ltlComment = (Literal)e.Item.FindControl( "ltlComment" );
ltlComment.Text = Server.HtmlEncode(currentComment.Comment);
ltlComment.Text = ltlComment.Text.Replace("<!br!>", "<br>");
}
}
Edited by SomeNewKid. Please post code between
<code> and
</code> tags.