I've noticed a most annoying (possible) bug in ASP.NET MVC's TextAreaFor HTML helper. For some reason, the HTML helper adds a NewLine before any content in the textarea. Apparently, this is to combat the possible issue of an individual's content beginning with a new line on purpose, and the browser ignoring it as per spec.
However, by adding it, I get the MUCH more annoying bug that now in all of my textareas automatically have an extra line before any content on form load (i.e. this shows up before any content in my field: ). It would appear that something is encoding the "newline" before spitting it out.
Anyone have a workaround for this? I'd expect that the intended behavior is for it to print out
<textarea>
Stuff</textarea>
not the
<textarea> Stuff</textarea>
I'm getting...
Edit Upon further inspection, it appears this is due to my using the AntiXssLibrary for encoding instead of the default HtmlEncoder. I am using version 4.0, and my encoder class method looks like this:
protected override void HtmlEncode(string value, TextWriter output)
{
output.Write(Microsoft.Security.Application.Encoder.HtmlEncode(value));
}
So my THOUGHT is that since the TagBuilder class, which is called from the TextAreaHelper, HTML encodes the contents of the tag, it is ASSUMING the behavior of the default HTML encoder, but the AntiXssLibrary is more thorough, and thus you see this behavior?
After doing some code digging, I've found that my thought is correct. The MVC3 TextArea HTML Helper uses the TagBuilder class, and does the following:
tagBuilder.SetInnerText(Environment.NewLine + value);
As SetInnerText calls HttpUtility.Encode on the contents of the argument passed to it, this results in the default encoder being called not just on the actual VALUE, but on this Environment.NewLine as well, meaning that if you aren't using the default HtmlEncoder (like the AntiXssLibrary instead), there could be some unexpected behavior, like this.
The fix would be for them to instead call:
tagBuilder.InnerHtml = Environment.NewLine + HttpUtility.Encode(value);
I have submitted a bug report.
In the mean time, I am implementing a Javascript onLoad fix to remove the offending encoding from all textareas:
$("textarea").each(function () { $(this).val($(this).val().trim()); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With