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.
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 !