asp.net-mvc - MVC3、 Razor 、Html.TextAreaFor() : adjust height to fit contents

标签 asp.net-mvc razor html-helper

我当前正在 View 中使用以下代码来调整 Html.TextAreaFor() 的高度以适合其内容。有没有更好和/或更简洁的方法来做到这一点?

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

...

最佳答案

代码看起来不错。一种可能的改进是将其外部化为可重用的助手,以避免污染 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);
    }
}

在 View 中:

@Html.TextAreaAutoSizeFor(m => m.Text, new { id = "text" })

关于asp.net-mvc - MVC3、 Razor 、Html.TextAreaFor() : adjust height to fit contents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10217651/

相关文章:

c# - ASP.NET MVC 应用程序的体系结构

asp.net - 在数据库表中有效地查找唯一值

javascript - Html lang 属性未出现在页面源代码中

.net - 将@section 放入@if .net mvc 3

c# - 您是否总是必须设置 ViewBag 变量才能从 Controller 访问数据

javascript - 在razor中使用javascript转换模型属性值

c# - ASP MVC 5 - 扩展身份 2.0

c# - ASP.NET 5 中 System.Web.Mvc.Html.InputExtensions 的等价物是什么?

.net - Html.HiddenFor 有什么作用?

php - Cakephp Html 助手结构