自定义Html.LabelFor

时间:2015-05-19 05:35:13

标签: asp.net-mvc razor mvc-editor-templates

我想在我的标签上添加一些课程,因此我在Label.cshtml文件夹下添加了Shared/EditorTemplates。似乎Razor无视它。我也试过了DisplayTemplates文件夹,但它也没有用。

我可以为标签设置编辑器模板吗?如果不是,那么定制它们的最佳方式是什么?

Label.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());
    }
}

2 个答案:

答案 0 :(得分:1)

EditorTemplate and DisplayTemplate基于属性类型。您可以creating your own HTML helper执行此操作。

public static class LabelExtensions
 {
      public static string Label(this HtmlHelper helper, string target, string text)
      {
           return String.Format("<label for='{0}'>{1}</label>", target, text);

      }
 }

答案 1 :(得分:1)

EditorTemplate基于属性的类型(不在他们生成的html元素上)。您需要创建自己的html帮助器

public static MvcHtmlString BootstrapLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
  var attributes = new { @class = "col-xs-4 control-label" };
  return helper.LabelFor(expression, attributes);
}

并在视图中将其用作

@Html.BootstrapLabelFor(m => m.yourProperty)

然而,这似乎是一种不灵活的方式来使用帮助器来保存在标准LabelFor()帮助器中添加html属性。根据{{​​3}},在一个帮助器中组合关联的文本框和验证消息可能更有用(请注意,此答案还说明了如何将命名空间添加到web.config文件

相关问题