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:
and in the view: