我总是使用HtmlHelpers,最常见的是封装样板HTML的代,以防我改变主意。我有这样的帮手:
- Html.BodyId():生成一个传统的身份标记标记为引用添加自定义CSS视图。
- Html.SubmitButton(string):根据我想要如何设置按钮的样式,生成一个输入[type = submit]或按钮[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,您的所有标签,输入,提示和验证消息都在您的页面上。同样,您可以在模型上使用属性并反思它们以获得真正的智能和干燥。当然,如果你无法标准化你的表单设计,这将浪费时间。但是,对于简单的情况,哪里可以提供您需要的所有自定义,它可以运行grrrrrrrrreat!
故事的道德 - HtmlHelpers可以让您免受全球设计变更的影响,在视图之后破坏手工制作的标记。我喜欢他们。但是你可以放弃,有时候部分视图比编码助手更好。 我用来决定助手还是局部视图的一般经验法则是:如果HTML块需要大量的条件逻辑或编码技巧,我使用助手(把代码放在代码应该在的地方)。如果不是,如果我只是输出普通标记没有太多的逻辑,我使用部分视图(把标记应放在标记)。
希望这给你一些想法!
我仍然对使用自定义HTML助手看到其他任何有趣的事情感兴趣。随意张贴! – stephen776 2011-01-26 14:38:32