我一直使用 HtmlHelpers,最常用的是封装样板 HTML 的生成,以防我改变主意。我有过这样的帮手:
- Html.BodyId():为视图添加自定义 css 时生成一个常规的 body id 标签供参考。
- Html.SubmitButton(string):生成 input[type=submit] 或 button[type=submit] 元素,具体取决于我要如何设置按钮的样式。
- Html.Pager(IPagedList):用于从分页列表模型生成分页控件。
- 等等……
我最喜欢 HtmlHelpers 的一个用途是干掉常见的表单标记。通常,我有一个容器 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)
{
// Can do all sorts of things here -- eg: reflect over attributes and add hints, etc...
}
不过,一旦你这样做了,你可以像这样输出表格行:
<%: Html.FormLineEditorFor(model => model.Property1) %>
<%: Html.FormLineEditorFor(model => model.Property2) %>
<%: Html.FormLineEditorFor(model => model.Property3) %>
...和 BAM,您的所有标签、输入、提示和验证消息都在您的页面上。同样,您可以在模型上使用属性并对其进行反思以变得非常聪明和干燥。当然,如果您不能标准化您的表单设计,这将是浪费时间。但是,对于简单的情况,css 可以提供您需要的所有自定义,它可以工作 grrrrrrrreat!
故事的寓意——HtmlHelpers 可以使您免受全球设计变化的影响,这些变化会在一个又一个视图中破坏手工制作的标记。我喜欢他们。但是你可能会过火,有时部分视图比编码的助手更好。 我用来决定辅助视图还是部分视图的一般经验法则:如果 HTML 块需要大量条件逻辑或编码技巧,我会使用辅助函数(将代码放在代码应该在的位置);如果不是,如果我只是输出普通标记而没有太多逻辑,我会使用局部视图(将标记放在应该标记的位置)。
希望这能给你一些想法!