I'm rendering a usual textarea like this:
@Html.TextAreaFor(x => x.Description)
I expected to see an empty textarea but here is what I see instead (I selected the first line to make it more clear):
I checked out the generated html and it contains a line break between an opening and closing tags:
<textarea class="form-control" cols="20" id="Description" name="Description" rows="2">
</textarea>
Is that done by design? Can I change this behaviour?
After saw your question, I research on Google to see what is the issue behind extra line in @Html.TextAreaFor
. Have a look.
There are some articles those are related to your issue:-
http://www.peschuster.de/2011/11/new-line-bug-in-asp-net-mvcs-textarea-helper/
ASP.NET MVC Textarea HTML helper adding lines when using AntiXssLibrary
Articles suggested that basic issue in TextAreaHelper
class which is used by @Html.TextAreaFor
.
private static MvcHtmlString TextAreaHelper(HtmlHelper htmlHelper,
ModelMetadata modelMetadata, string name, IDictionary<string,
object> rowsAndColumns, IDictionary<string, object> htmlAttributes)
{
// Some initialization here...
TagBuilder tagBuilder = new TagBuilder("textarea");
// Some more logic...
tagBuilder.SetInnerText(Environment.NewLine + attemptedValue);
return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}
and the issue in above code is
tagBuilder.SetInnerText(Environment.NewLine + attemptedValue);
That's why actual output of @Html.TextAreaFor
will be like this and extra line shows up:-
<textarea> This is the content...</textarea>
The workaround of this problem is to
1st Workaround Implementing a Javascript onLoad fix to remove the offending encoding from all textareas:
$("textarea").each(function () { $(this).val($(this).val().trim()); });
2nd Workaround create your own helper for rendering textarea markup in views
public static MvcHtmlString FixedTextAreaFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return new MvcHtmlString(htmlHelper.TextAreaFor(expression)
.ToHtmlString()
.Replace("> ", ">" + Environment.NewLine));
}
These articles also suggested that this problem will be fixed in MVC 4 Developer Preview!
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