1

I'd like to add some classes to my labels, so I added Label.cshtml Under Shared/EditorTemplates folder. It seems Razor is ignoring it. I've tried DisplayTemplatesfolder too, but it didn't work neither.

Can I have editor template for labels? If no, what's the best way to customize them?

Label.cshtml:

@model object

@Html.LabelFor(m => m, new { @class = "col-xs-4 control-label" })

UPDATE:

This is my code that I took from this post and with some changes from this useful link. It still doesn't work, I don't know what's going on. Can anyone help?

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());
    }
}
Community
  • 1
  • 1
Akbari
  • 2,369
  • 7
  • 45
  • 85
  • 1
    `EditorTemplate`'s are based on the type of a property (not on the html element they generate). You would need to create your own html helper –  May 19 '15 at 05:44

2 Answers2

2

EditorTemplate's are based on the type of a property (not on the html element they generate). You would need to create your own html helper

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);
}

and use it in the view as

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

However this seems an inflexible way to use a helper just to save adding the html attributes in the standard LabelFor() helper. Perhaps it might be more useful to combine the associated textbox and validation message in the one helper as per this answer (Note this answer also shows how to add the namespace to the web.config file

Community
  • 1
  • 1
  • Thanks Stephen, but now I'm trying to add an extension for labelfor, so hopefully I don't have to change my code. – Akbari May 19 '15 at 07:46
  • What do you mean? This **is** an extension method (that renders a label with the class name) –  May 19 '15 at 07:47
  • I'm mean I want to somewhat overwrite default behavior of `Labelfor` to add my classes in it. Please look at the code I've enclosed at the bottom of my question. – Akbari May 19 '15 at 07:50
  • Which is exactly what this does (and its the only way to do it) –  May 19 '15 at 07:50
  • Well, with this code you have to use `@Html.BootstrapLabelFor`, not `Html.LabelFor`. Am I missing something? – Akbari May 19 '15 at 07:53
  • You cant use the built in `Html.LabelFor()` You need to create you own method! It has to have a different name. –  May 19 '15 at 07:55
  • Thanks for your time and patience Stephen, isn't there anyway to add an overload on it? – Akbari May 19 '15 at 07:57
  • 1
    Not unless you give it a completely different, non ambiguous signature, or fully qualify the method name e.g. for the standard helpers you would need to use `@System.Web.Mvc.Html.LabelExtensions.LabelFor(Html, m => m.YourProperty)` and you would need to do something similar based on your assembly and class names. (you end up typing more that you would have using the in built helper) –  May 19 '15 at 08:02
1

EditorTemplate and DisplayTemplate are based on property type. You'd do this by 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);

      }
 }
Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110
  • 1
    Not only is that not adding the html attributes, its not the correct way to generate the element and will not create a sanitized id attribute. Suggest you explore the [source code](https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/LabelExtensions.cs). –  May 19 '15 at 05:55