I'm currently using the following code in the View to adjust the height of a Html.TextAreaFor() to fit its contents. Is there a significantly better &/or less verbose way to do this?
...
int width = 85;
int lines = 1;
string[] arr = Model.Text.Split(new string[] {"\r\n", "\n", "\r"}, StringSplitOptions.None);
foreach (var str in arr)
{
if (str.Length / width > 0)
{
lines += str.Length / width + (str.Length % width <= width/2 ? 1 : 0);
}
else
{
lines++;
}
}
@Html.TextAreaFor(m => m.Text,
new
{
id = "text",
style = "width:" + width + "em; height:" + lines + "em;"
})
...
The code looks fine. One possible improvement would be to externalize it into a reusable helper to avoid polluting the view:
public static class TextAreaExtensions
{
public static IHtmlString TextAreaAutoSizeFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes
)
{
var model = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model;
var text = model as string ?? string.Empty;
int width = 85;
int lines = 1;
string[] arr = text.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
foreach (var str in arr)
{
if (str.Length / width > 0)
{
lines += str.Length / width + (str.Length % width <= width / 2 ? 1 : 0);
}
else
{
lines++;
}
}
var attributes = new RouteValueDictionary(htmlAttributes);
attributes["style"] = string.Format("width:{0}em; height:{1}em;", width, lines);
return htmlHelper.TextAreaFor(expression, attributes);
}
}
and in the view:
@Html.TextAreaAutoSizeFor(m => m.Text, new { id = "text" })
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