我有一些名称较长的实体,我希望能够使用HTML abbr
标记在标签中缩写它们。我使用DataAnnotations为视图模型(或实体类)中的属性提供DisplayName值。
我已经手动执行此操作:
<label class="myClass"><abbr title="@Html.DisplayFor(m => m.Ssn)">SSN</abbr> @Html.EditorFor(m => m.Ssn)</label>
但它变得很痛苦。我想用以下语法设计一个帮助器。
@Html.AbbrLabelFor(m => m.Ssn, "SSN")
和输出:
<label for="Ssn"><abbr title="Social Security Number">SSN</abbr></label>
其中&#34;社会安全号码&#34;是DisplayName值,helper标记中的第二个参数是缩写文本。所以基本上只是添加第二个参数。
我见过的例子往往会抛弃HtmlAttributes等等,我希望保留这些功能,如:
@Html.AbbrLabelFor(m => m.Ssn, "SSN", new { @class="myClass" })
如何扩展现有的全功能LabelFor来实现它,DfnLabel等?
答案 0 :(得分:2)
你的助手需要看起来像
public static MvcHtmlString AbbrLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string abbreviation, object htmlAttributes)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression)
TagBuilder abbr = new TagBuilder("abbr");
abbr.MergeAttribute("title", metaData.GetDisplayName());
abbr.InnerHtml = abbreviation;
TagBuilder label = new TagBuilder("label");
label.MergeAttribute("for", name);
label.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
label.InnerHtml = abbr.ToString();
return MvcHtmlString.Create(label.ToString());
}
编辑(带有重载)
public static MvcHtmlString AbbrLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string abbreviation)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
return AbbrLabelHelper(helper, metaData, name, abbreviation, null);
}
public static MvcHtmlString AbbrLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string abbreviation, object htmlAttributes)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
return AbbrLabelHelper(helper, metaData, name, abbreviation, htmlAttributes);
}
private static MvcHtmlString AbbrLabelHelper(HtmlHelper helper, ModelMetadata metaData, string name, string abbreviation, object htmlAttributes)
{
TagBuilder abbr = new TagBuilder("abbr");
abbr.MergeAttribute("title", metaData.GetDisplayName());
abbr.InnerHtml = abbreviation;
TagBuilder label = new TagBuilder("label");
label.MergeAttribute("for", name);
label.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
label.InnerHtml = abbr.ToString();
return MvcHtmlString.Create(label.ToString());
}