Asp.net mvc ASP.NET MVC 3自定义HTML帮助程序-最佳实践/使用

Asp.net mvc ASP.NET MVC 3自定义HTML帮助程序-最佳实践/使用,asp.net-mvc,asp.net-mvc-2,asp.net-mvc-3,html-helper,Asp.net Mvc,Asp.net Mvc 2,Asp.net Mvc 3,Html Helper,MVC新手,已经在asp.net网站上运行了教程 它们包括一个自定义html帮助器的示例,用于截断表中显示的长文本 只是想知道人们在使用HTML助手时想出了哪些其他解决方案,以及在创建/使用它们时是否有任何最佳实践或需要避免的事情 例如,我曾考虑编写一个自定义助手来格式化需要在不同位置显示的日期,但现在担心可能会有一个更优雅的解决方案(即模型中的DataAnnotation) 有什么想法吗 编辑: 我刚刚想到的另一个潜在用途是……字符串连接。 自定义帮助程序可以接受用户ID作为输入并返回用户全名

MVC新手,已经在asp.net网站上运行了教程

它们包括一个自定义html帮助器的示例,用于截断表中显示的长文本

只是想知道人们在使用HTML助手时想出了哪些其他解决方案,以及在创建/使用它们时是否有任何最佳实践或需要避免的事情

例如,我曾考虑编写一个自定义助手来格式化需要在不同位置显示的日期,但现在担心可能会有一个更优雅的解决方案(即模型中的DataAnnotation)

有什么想法吗

编辑:

我刚刚想到的另一个潜在用途是……字符串连接。 自定义帮助程序可以接受用户ID作为输入并返回用户全名。。。
结果可能是某种形式的(Title)(First)(Middle)(Last),具体取决于哪些字段可用。只是想一想,我还没有尝试过这样的事情

在格式化属性的情况下,这可能是一个很好的解决方案:

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime Date { get; set; }
然后简单地说:

@Html.DisplayFor(x => x.Date)
就截断字符串而言,定制HTML助手是一个很好的解决方案


更新:

关于编辑,在这种情况下可以使用自定义HTML助手,但我也非常喜欢另一种方法:视图模型。因此,如果在这个特定视图中,您总是要显示名称的串联,那么您可以定义一个视图模型:

public class PersonViewModel
{
    public string FullName { get; set; }
}

现在,控制器将查询存储库以获取模型,然后将该模型映射到一个视图模型,该视图模型将被传递到视图,这样视图就可以简单地
@Html.DisplayFor(x=>x.FullName)
。模型和视图模型之间的映射可以通过类似的框架来简化。

我一直使用HtmlHelpers,最常见的是封装样板HTML的生成,以防我改变主意。我有这样的助手:

  • Html.BodyId():为视图添加自定义css时,生成常规的主体id标记以供引用
  • SubmitButton(string):生成输入[type=submit]或按钮[type=submit]元素,具体取决于我想要如何设置按钮的样式
  • 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...
}    
public static MvcHtmlString FormLineDropDownListFor(此HtmlHelper帮助程序、表达式、IEnumerable selectList、字符串labelText=null、字符串customHelpText=null、对象htmlAttributes=null)
{
返回模板行(
LabelFor(表达式,labelText.ToString())+
helper.HelpTextFor(表达式,customHelpText),
DropDownListFor(表达式、选择列表、htmlAttributes).ToString()+
ValidationMessageFor(表达式));
}
public static MvcHtmlString FormLineEditorFor(此HtmlHelper帮助程序,表达式,字符串templateName=null,字符串labelText=null,字符串customHelpText=null,对象htmlAttributes=null)
{
返回模板行(
LabelFor(表达式,labelText.ToString())+
helper.HelpTextFor(表达式,customHelpText),
EditorFor(表达式、模板名、htmlAttributes).ToString()+
ValidationMessageFor(表达式));
}
私有静态MvcHtmlString FormLine(字符串labelContent、字符串fieldContent、对象htmlAttributes=null)
{
var editorLabel=新标记生成器(“div”);
editorLabel.AddCssClass(“编辑标签”);
editorLabel.InnerHtml+=labelContent;
var editorField=新标记生成器(“div”);
editorField.AddCssClass(“编辑器字段”);
editorField.InnerHtml+=字段内容;
var容器=新标记生成器(“div”);
如果(htmlAttributes!=null)
MergeAttributes(新的RouteValueDictionary(htmlAttributes));
容器。添加CSSClass(“格式行”);
container.InnerHtml+=编辑器标签;
container.InnerHtml+=editorField;
返回MvcHtmlString.Create(container.ToString());
}
公共静态MvcHtmlString HelpTextFor(此HtmlHelper helper,表达式,字符串customText=null)
{
//可以在这里做各种事情——例如:反射属性和添加提示等。。。
}    
完成此操作后,您可以像这样输出表单行:

<%: Html.FormLineEditorFor(model => model.Property1) %>
<%: Html.FormLineEditorFor(model => model.Property2) %>
<%: Html.FormLineEditorFor(model => model.Property3) %>
model.Property1)%%>
模型.属性2)%>
模型.属性3)%>
。。。BAM,所有标签、输入、提示和验证消息都在页面上。同样,您可以在模型上使用属性并对其进行反射,以获得真正的智能和干爽。当然,如果不能对表单设计进行标准化,这将是浪费时间。然而,对于简单的情况,css可以提供您所需的所有定制,它可以正常工作

这个故事的寓意是——HtmlHelpers可以使您免受全局设计更改的影响,这些更改会在一个又一个视图中破坏手工制作的标记。我喜欢它们。但您可能会过火,有时局部视图比编码的帮助器更好我用于在helper和partial view之间做出决定的一般经验法则:如果HTML块需要大量条件逻辑或编码技巧,我使用helper(将代码放在应该放的地方);如果不是,如果我只是输出公共标记而没有太多逻辑,我将使用局部视图(将标记放在标记应该放的位置)。

希望这能给你一些想法

公共静态HtmlString OwnControlName(此HtmlHelper帮助程序,表达式,字符串标签\名称=”,字符串标签\标题=”,属性属性=null)
public static HtmlString OwnControlName<T, U>(this HtmlHelper<T> helper, Expression<Func<T, U>> expression, string label_Name = "", string label_Title = "", Attr attr = null)
        {
            TemplateBuilder tb = null;
            string template = null;
          if (expression == null) throw new ArgumentException("expression");
 obj = helper.ViewData.Model;
                tb.Build(obj, expression.Body as MemberExpression, typeof(T), new SimpleTemplate(new TextArea()), label_Name, label_Title, attr);
                template = tb.Get();
 return new MvcHtmlString(template);
}
{ TemplateBuilder tb=null; 字符串模板=null; if(表达式)