Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3, Razor, Html.TextAreaFor(): adjust height to fit contents

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;"
                  })

...
like image 906
Handprint Avatar asked Dec 27 '22 02:12

Handprint


1 Answers

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" })
like image 115
Darin Dimitrov Avatar answered Jan 14 '23 10:01

Darin Dimitrov