Html.TextArea generates extra line break by default

I create a plain text space like this:

@Html.TextAreaFor(x => x.Description) 

I expected to see an empty text box, but here is what I see (I selected the first line to make it more understandable):

enter image description here

I checked the generated html and it contains a line break between the opening and closing tags:

 <textarea class="form-control" cols="20" id="Description" name="Description" rows="2"> </textarea> 

Is it made by design? Can I change this behavior?

+5
source share
1 answer

After you saw your question, I study Google to find out what the problem of the extra line in @Html.TextAreaFor . Take a look.

There are several articles that are related to your problem: -

http://www.peschuster.de/2011/11/new-line-bug-in-asp-net-mvcs-textarea-helper/

ASP.NET MVC Textarea HTML Helper Adding Strings When Using AntiXssLibrary

The articles suggested the main problem in the 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 problem is in the above code

 tagBuilder.SetInnerText(Environment.NewLine + attemptedValue); 

So, the actual output of @Html.TextAreaFor will be like this and an extra line will appear: -

 <textarea>&#13;&#10;This is the content...</textarea> 

The workaround for this problem is

1st solution Implementation of the Javascript onLoad patch to remove encoding that violates all text areas:

 $("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 issue would be fixed in MVC 4 Developer Preview!

+5
source

Source: https://habr.com/ru/post/1206724/


All Articles