我经常使用HtmlHelpers,最常见的是封装HTML样板生成,以防我改变主意。 我有一些这样的帮助程序:
- Html.BodyId():生成传统的body id标记,用于在视图中添加自定义css时进行引用。
- Html.SubmitButton(string):生成input[type=submit]或button[type=submit]元素,具体取决于我想如何设置按钮样式。
- Html.Pager(IPagedList):用于从分页列表模型生成分页控件。
- 等等....
我的一个最喜欢的HtmlHelpers用途是DRY(不要重复自己)常见的表单标记。 通常,我有一个包含表单行的容器div,一个用于标签的div,以及一个用于输入,验证消息,提示文本等的标签。 最终,这可能会成为大量的样板HTML标记。 下面是我处理此问题的示例:
public static MvcHtmlString FormLineDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string labelText = null, string customHelpText = null, object htmlAttributes = null)
{
return FormLine(
helper.LabelFor(expression, labelText).ToString() +
helper.HelpTextFor(expression, customHelpText),
helper.DropDownListFor(expression, selectList, htmlAttributes).ToString() +
helper.ValidationMessageFor(expression));
}
public static MvcHtmlString FormLineEditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string templateName = null, string labelText = null, string customHelpText = null, object htmlAttributes = null)
{
return FormLine(
helper.LabelFor(expression, labelText).ToString() +
helper.HelpTextFor(expression, customHelpText),
helper.EditorFor(expression, templateName, htmlAttributes).ToString() +
helper.ValidationMessageFor(expression));
}
private static MvcHtmlString FormLine(string labelContent, string fieldContent, object htmlAttributes = null)
{
var editorLabel = new TagBuilder("div");
editorLabel.AddCssClass("editor-label");
editorLabel.InnerHtml += labelContent;
var editorField = new TagBuilder("div");
editorField.AddCssClass("editor-field");
editorField.InnerHtml += fieldContent;
var container = new TagBuilder("div");
if (htmlAttributes != null)
container.MergeAttributes(new RouteValueDictionary(htmlAttributes));
container.AddCssClass("form-line");
container.InnerHtml += editorLabel;
container.InnerHtml += editorField;
return MvcHtmlString.Create(container.ToString());
}
public static MvcHtmlString HelpTextFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string customText = null)
{
}
一旦您完成了这个步骤,您就可以像这样输出表单行:
<%: Html.FormLineEditorFor(model => model.Property1) %>
<%: Html.FormLineEditorFor(model => model.Property2) %>
<%: Html.FormLineEditorFor(model => model.Property3) %>
当你使用HtmlHelpers时,只需添加属性到你的模型中,就可以在页面上显示所有标签、输入框、提示和验证信息。你可以反射这些属性,让你的代码更加智能和DRY。当然,如果你不能在表单设计上达成标准化,这将是一种浪费时间的做法。但是,在简单情况下,如果css可以提供你所需的所有自定义内容,那么它的效果会非常好!
故事的寓意是-- HtmlHelpers可以使你免受全局设计变化破坏手工标记的影响。我喜欢他们。但是你可能会过度使用,有时候部分视图比编码帮助器更好。我用于决定使用帮助器还是部分视图的一个通用原则是:如果HTML块需要大量的条件逻辑或编码技巧,我使用帮助器(把代码放在应该放置代码的地方);否则,如果我只是输出没有太多逻辑的公共标记,我使用部分视图(把标记放在应该放置标记的地方)。
希望这给你一些启示!