Line breaks are being lost when sending text to the Database - asp.net

For some reason the line breakes from ASP.NET textboxes are not being stored in my database.
I am using Server.HtmlEncode(txtAbout.Text) to take the text from the textbox.
This part works and text is taken out with line breaks.
But when I trace the text, the line breaks are lost after this line:
db.AddInParameter(dbCommand, "About", DbType.String, about);
db.ExecuteNonQuery(dbCommand);
In the stored procedure the varable #about is ntext.
In the table the column about is ntext
I hope someone can help.

Could you trace what the value of "about" is before sending it off to the stored procedure?
I suspect what is happening is when you are outputting the stored result, you are assigning it to a label. Rather output it to a literal:
<asp:Literal runat="server" id="litAbout" />
Then once you have done that, then do the "placement". For example:
litAbout.Text = Server.HtmlEncode(aboutText).Replace(Environment.NewLine, "<br/>");
Also, that is where you want to encode the output. You almost always only do the final transformations prior to outputting the result; the thinking is that you don't want to lose that raw input.

Outputting to a label isn't the problem. The problem is outputting it to a label without doing the replace Justin mentioned.
I just tested this in VS2010 (.NET 3.5) and it worked.
<asp:Label runat="server" ID="lblAbout" />
lblAbout.Text = Server.HtmlEncode(aboutText).Replace(Environment.Newline, "<br />");
This solution will work the same as the literal.

Related

New Line Character not Recognized in ASP .Net Text Box

I want to display the data with new line in text box. I am saving the comment in DB and then displaying the data on the UI.
The below is the .aspx code :-
<asp:TextBox ID="comment" TextMode="MultiLine" runat="server"
Rows="5" Columns="100" CssClass="multiline-text"></asp:TextBox>
Here is my DB Comment :-
This is test Comment./r/n Please do some reply on this.
How its showing on UI :-
This is test Comment./r/n Please do some reply on this.
Then I updated DB Comment :-
This is test Comment.<br /> Please do some reply on this.
How its showing on UI :-
This is test Comment.<br /> Please do some reply on this.
What I can change in asp .net file or in DB so that the data displays with new line in text box.
There are a few things to mention here:
You are actually using wrong escape sequences, it should be \r\n (backslash instead of slash)
If you get this data from somewhere else (e.g. the database), it probably would be correctly escaped
Consider check the string while debugging to verify what's actually coming from your source
When you've verified the text, you can then replace the necessary characters by correct escape characters:
Assuming this is coming as text in a variable myText:
This is test Comment.\r\n Please do some reply on this.
then you can think of This is test Comment.\\r\\n Please do some reply on this.
and you can do the following:
comment.Text = myText.Replace("\\r\\n", "\n"); // replace text "\r\n" by a new line escape sequence
You can use Wrap Property which display ASP.Net TextBox with multiline property to automatically continues on next line when it reaches the end.
<asp:TextBox ID="comment" TextMode="MultiLine" runat="server" Wrap="true" Rows="5" Columns="100" CssClass="multiline-text"></asp:TextBox>
Additionally, you can add this line in your css class to make sure proper lines break at <br> and preserve white space.
word-wrap: break-word;

The server tag is not well formed. When passing parameters to javascript function

Hi have always trouble with calling JavaScript function with parameters values as values bonded to the gridview. I follow SO Thread But can not used for passing this parameter . Below is the statement that I used in my aspx page.
onblur="return ValidateText(this,'<%# Eval("vehicleId") %>')"
But this gives me parsing error The server tag is not well formed. How should I call this function in design only(not from code behind).
This works, but seems an HACK because I removed the enclosing quotes (anti-XHtml)
onblur=<%# String.Format("return ValidateText(this, '{0}')", Eval("VehicleID")) %>
The problem is having " "" " or ' '' ' as part of the string.
This is better done (I wish it is easier in markup), in code-behind, e.g. RowDataBound or ItemDataBound
control.Attributes["onblur"] = String.Format("return ValidateText(this, '{0}')", rowValue);
I think the problem is the outer-most double quotes ", change that to single quotes '.
onblur='return ValidateText(this,'<%# Eval("vehicleId") %>')'
UPDATE
Try using string.Format() as mentioned in the SO question your are refering..
onblur='<%# System.String.Format("return ValidateText(this, \"{0}\")", Eval("vehicleId")) %>'

Replace(Environment.NewLine, "<br/>") is not working as expected when displaying text on a web page

I'm not sure why the following code is not working as intended:
litMessage.Text = messageBody.Replace(Environment.NewLine, "<br/>")
Where litMessage is the name of the literal control and messageBody is the name of the string variable.
My intention is to output a string onto a web page and to replace the line breaks with a br tag so that it can be displayed on the page correctly. However, nothing is replaced. When viewing the page source, it looks like the line breaks still exist in the string. Similarly, when displaying the string via MsgBox, it displays normally as well. I have also tried wrapping the output with the pre tag and it displays the line breaks properly as well.
The string was originally entered by a user through the use of an asp:Textbox and saved into a MSSQL database. It's retrieved and displayed on another webpage using an asp:Literal control. The only thing that happens to the string before it is submitted is that it is trimmed (i.e. textbox.Text.Trim()).
Perhaps there is something I did not consider?
Edit #1: Due to time constraints, I've decided to just wrap the text with the pre tag. It's an acceptable work around as it preserves the line breaks. Unfortunately, it doesn't explain why the code didn't work in the first place. In the meantime, I'll just leave the question unanswered until I find a proper answer.
Edit #2: Solution found and answered below. UpdatePanel tag added to the question for future reference.
After revisiting this issue, I have found that updatepanels were causing the problem.
Doing some more testing, I looked into what the string contained using the following code:
MsgBox(textbox.Text.Contains(vbCr))
MsgBox(textbox.Text.Contains(vbCrLf))
MsgBox(textbox.Text.Contains(vbNewLine))
MsgBox(textbox.Text.Contains(Environment.Newline))
All four statements returned false. This was tested on the string before sending to the database as well as on the string retrieved from the database.
From my point of view, there had to be something on the markup that was removing the line breaks. At first, I thought the Literal, Textbox, and Label controls did something funny to line breaks when retrieved in the code behind. This is not the case (and would be bizarre if Microsoft let this happen).
Combing through the code some more, I found that all these controls were inside an UpdatePanel. Remembering my previous negative experiences with UpdatePanels, I then thought that this might just be the culprit. I removed it and lo and behold, the line breaks did not go away in the code. The code I posted just above all returned true.
Both pages had the controls for submitting the text and displaying the text inside an UpdatePanel. I found that the line breaks disappeared when retrieving the text from the page. When displaying the text onto the page, the UpdatePanel does not alter the string in any way. The following code ended up working just fine:
litMessage.Text = messageBody.Replace(Environment.NewLine, "<br/>")
Although I'm still not sure why line breaks were still displayed correctly when using the pre tag or even displaying the retrieved value using a javascript alert box.
It's hard to say from the code you've posted, but if you're passing the myString varaible itself to the page (and not the return value of the Replace function) you'll need to do -
myString = myString.Replace(Environment.NewLine, "<br/>")
before passing it to the page.
If you use an UPDATEPANEL the myText..Replace(Environment.NewLine, "<br/>") WILL NOT WORK. I found out the hard way (spent 2 hours already)
The solution (when using updatepanel) is to set a "PostBackTrigger" like this:
<asp:UpdatePanel runat="server" ID="pnlUpdate" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="btnDoThatShitAlready" />
</Triggers>
Just found this while looking for a solution for replace not working with text in the literal control while it resides within a formview. The way I solved it was, in the databinding for the literal, to pass the text to a string, do the replace on the string then put the processed text back into the literal's text field.
Protected Sub MyLit_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim text1 As String
text1 = CType(myFormView.FindControl("MyLit"), Literal).Text
text1 = Replace(text1, Environment.NewLine, "<br />")
CType(myFormView.FindControl("MyLit"), Literal).Text = text1
End Sub
I hope this helps you, and anyone else who might visit this site for a solution.
Regarding the 4 tests above that failed (author: nullexception)...
MsgBox(textbox.Text.Contains(vbCr))
MsgBox(textbox.Text.Contains(vbCrLf))
MsgBox(textbox.Text.Contains(vbNewLine))
MsgBox(textbox.Text.Contains(Environment.Newline))
I tried those tests and they failed for me as well. Then, I noticed there was no test for just vbLf, so I tested it. BINGO! That was it!
So, this works...
Label.Text = MultiLineTextBox.Text.Replace(ControlChars.Lf, "<br />")
I wasted my two hours finding what was actually wrong.
Well, solution is instead of Environment.NewLine, use ControlChars.Lf
You can remove updatepanel which will sort out the problem for future data. But if you already have some data, using ControlChars.Lf will help.
You can use it like this, because the System.NewLine returns a "\r\n" string
dim messageBody as string = "some text here";
litMessage.Text = messageBody.Replace("\r\n", "< br />");
litMessage.Text = messageBody.Replace("\\\\n","< br />").Replace(Environment.NewLine, "< br />")
It has worked for me. Hope this might work for you as well.
var str = "Text sample to replace carriage return + newline ("
+ (char)13 + (char)10
+ #") and
the Environment.NewLine and "
+ Environment.NewLine
+ " and the unix \n new line character.";
str.Replace("\r\n","<br />")
.Replace(Environment.NewLine, "<br />")
.Replace("\n", "<br />");
The output is
Text sample to replace carriage return + newline (<br />) and<br /> the Environment.NewLine and <br /> and the unix <br /> new line character.
To put the label text next line we can use the below mentioned solution.
<asp:Label ID="lblAppointmentLocation" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Location").ToString().Replace(Environment.NewLine, "<br/>").Replace("\n", "<br />") %>'></asp:Label>
What you are really looking for is:
#Html.Raw(#Regex.Replace(input_to_be_printed_correctly, #"\r\n?|\n", "<br />"))
I'm using this code and it works :
Instead of
.Replace(Environment.NewLine, "<br/>")
use
.Replace("\n", "<br />")
Hope to be useful.

How can I write raw XML to a Label in ASP.NET

I am getting a block of XML back from a web service. The client wants to see this raw XML in a label on the page. When I try this:
lblXmlReturned.Text = returnedXml;
only the text gets displayed, without any of the XML tags. I need to include everything that gets returned from the web service.
This is a trimmed down sample of the XML being returned:
<Result Matches="1">
<VehicleData>
<Make>Volkswagen</Make>
<UK_History>false</UK_History>
</VehicleData>
<ABI>
<ABI_Code></ABI_Code>
<Advisory_Insurance_Group></Advisory_Insurance_Group>
</ABI>
<Risk_Indicators>
<Change_In_Colour>false</Change_In_Colour>
</Risk_Indicators>
<Valuation>
<Value xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></Value>
</Valuation>
<NCAP>
<Pre_2009></Pre_2009>
</NCAP>
</Result>
What can I do to make this appear on the screen? I noticed that Stack Overflow does a pretty good job of putting the XML on the scren. I checked the source and it's using <pre> tags. Is this something that I have have to use?
It would be easier to use a <asp:Literal /> with it's Mode set to Encode than to deal with manually encoding Label's Text
<asp:Literal runat="server" ID="Literal1" Mode="Encode" />
You need to HtmlEncode the XML first (which escapes special characters like < and > ):
string encodedXml = HttpUtility.HtmlEncode(xml);
Label1.Text = encodedXml;
Surrounding it in PRE tags would help preserve formatting, so you could do:
string encodedXml = String.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(xml));
Label1.Text = encodedXml;
As Bala R mentions, you could just use a Literal control with Mode="Encode" as this automatically HtmlEncodes any string. However, this would also encode any PRE tags you added into the string, which you wouldn't want. You could also use white-space:pre in CSS which should do the same thing as the PRE tag, I think.

html injection question

Using FreeTextBox, I'm capturing HTML-formatted text. The purpose is to allow a website owner to update their web page content on a few pages. I have the system completed except for knowing what to do with the resultant HTML markup.
After the page editor completes their work, I can get the output from FreeTextBox, in html format, like so: <font color="#000080"><b>This is some text.</b></font>
I tried storing it as escaped markup in web.config, but that didn't work since it kept hosing the tags even after I changed them to escaped characters, like so: <font color="#000080">
The reason I wanted to store this kind of string as a key in web.config is that I could successfully store a static string, set a lebel's value to it, and successfully render the text. But when I try to escape it, it gets reformatted in web.config by .Net somehow.
So I escaped all the characters, encoded them as Base64 and stored that. Then on page_load, I tried to decode it, but it just shows up as text, with all the html tags showing as well - it doesn't get rendered. I know a million people use this control, but I'm damned if I can figure out how to do it right.
So here's my question: how can I inject the saved HTML into an edited page so it shows up in browsers like the editor wants it to look?
Try Server.HtmlDecode to output the HTML to the screen.
As a side note, I prefer to use CKEditor for html-formatted input. I found it is the better option among all options (FreeTextBox, TinyMCE, anything else?) and it has got completely rewritten and faster in the version 3.0!
In case anyone comes here for the answer, here's one way to do it.
I had initial problems with web.config changing some of the HTML tags upon storage, so we use B64 encoding (may not be necessary). Store the saved html markup to an AppSettings key in web.config as Base64 encoding, using this for your setting update function. Add error checking and whatever else you need it to do:
'create configuration object
Dim cfg As Configuration
cfg = WebConfigurationManager.OpenWebConfiguration("~")
'get reference to appsettings("HTMLstring")
Dim HTMLString As KeyValueConfigurationElement = _
CType(cfg.AppSettings.Settings("HTMLstring"), KeyValueConfigurationElement)
'get text entered by user and marked up with HTML tags from FTB1, then
'encode as Base64 so we can store it as XML-safe string in web.config
Dim b64String As String = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(FTB1.Text))
'save new value into web.config
If Not HTMLString Is Nothing Then
HTMLString.Value = b64String
cfg.Save()
End If
Next, add a Literal control to the aspx markup:
<asp:Literal id="charHTML" runat="server"/>
To add the saved HTML to the post-edited page, do the following in Page_Load:
'this string of HTML code is stored in web.config as Base64 to preserve XML-unsafe characters that come from FreeTextBox.
Dim injectedHTML As String = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(AppSettings("HTMLstring")))
'the literal control will directly inject this HTML instead of encoding it
charHTML.Mode = LiteralMode.PassThrough
'set the value
charHTML.Text = injectedHTML
Hope this helps. sF

Resources