Han*_*int 4 asp.net-mvc html-helper razor
我目前在视图中使用以下代码来调整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;"
})
...
Run Code Online (Sandbox Code Playgroud)
代码看起来很好.一种可能的改进是将其外部化为可重用的帮助程序,以避免污染视图:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
并在视图中:
@Html.TextAreaAutoSizeFor(m => m.Text, new { id = "text" })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12601 次 |
| 最近记录: |