Add colons and stars to helper generated labels

1.4k views Asked by At

I'm using Razor and Data Annotations in a .NET 4.5 MVC app. This is from a view model:

    [Required(ErrorMessage = "Title is required.")]
    [Display(Name = "Title: *")]
    public string Title { get; set; }

    [Display(Name = "Comments:")]
    public string Comments { get; set; }

Is there a way to remove those display atributes and have a colon after the generated name (colon, space, star for a required field)? In the error messages the colon should not be shown.

2

There are 2 answers

1
Raphaël Althaus On BEST ANSWER

You could use your own Custom display helper (similar to LabelFor), or

If you want the LabelFor to be :

<PropertyName> :

and when you have a Required attribute

<PropertyName> : *

you could try to use a Custom DataAnnotationsModelMetadataProvider

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
        if (propertyName != null) {            
           metadata.DisplayName = (metadata.DisplayName ?? propertyName) + " : ";
           if (attributes.OfType<RequiredAttribute>().Any())
              metadata.DisplayName +=" * ";
         }
        return metadata;
    }
}

to use this, you have to put

ModelMetadataProviders.Current = new CustomModelMetadataProvider()

in the Application_Start() of your Global.asax.cs

Now, I'm not sure if metadata.DisplayName is used in the error messages... I let you test !

0
guitarlass On

Raaphaels solution worked for me. With that help i placed the following JavaScript into my layout file to color the asterisk red.

$('.control-label').each(function () {
   var textVal = $(this).html();
   if (textVal.indexOf("*") > 0) {
       var newTextVal = textVal.replace("*", "");
       $(this).html(newTextVal + "<span style='color:#ff0000'> *</a>");
   }
});