Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.TextArea generates extra line break by default

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):

enter image description here

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?

like image 893
SiberianGuy Avatar asked Nov 12 '14 14:11

SiberianGuy


1 Answers

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>&#13;&#10;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(">&#13;&#10;", ">" + Environment.NewLine));
}

These articles also suggested that this problem will be fixed in MVC 4 Developer Preview!

like image 187
HaveNoDisplayName Avatar answered Oct 20 '22 17:10

HaveNoDisplayName