【发布时间】:2015-05-19 05:35:13
【问题描述】:
我想给我的标签添加一些类,所以我在Shared/EditorTemplates 文件夹下添加了Label.cshtml。 Razor 似乎忽略了它。我也试过DisplayTemplatesfolder,但也没有用。
我可以有标签的编辑器模板吗?如果不是,自定义它们的最佳方式是什么?
标签.cshtml:
@model object
@Html.LabelFor(m => m, new { @class = "col-xs-4 control-label" })
更新:
这是我从this post 获取的代码,并从useful link 中进行了一些更改。它仍然不起作用,我不知道发生了什么。有人可以帮忙吗?
public static class Extensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
return LabelFor(html, expression, null);
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes){
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string FieldName = ExpressionHelper.GetExpressionText(expression);
string LabelText = metaData.DisplayName ?? metaData.PropertyName ?? FieldName.Split('.').Last();
if (string.IsNullOrEmpty(LabelText))
return MvcHtmlString.Empty;
TagBuilder tag = new TagBuilder("label");
tag.MergeAttributes(htmlAttributes);
tag.SetInnerText(LabelText);
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(FieldName));
tag.Attributes.Add("class", "control-label col-xs-2");
return MvcHtmlString.Create(tag.ToString());
}
}
【问题讨论】:
-
EditorTemplate's 基于属性的类型(而不是基于它们生成的 html 元素)。您需要创建自己的 html 助手
标签: asp.net-mvc razor mvc-editor-templates