My aim is very simple. I wanna get "Display Name" in Required Error Message. So I used it '{0}' that string format Example: sqlLocalization
[Required(ErrorMessage="The {0} field is required.")]
public class AttributeField
{
[Display(Name = "AttributeFeatureCode")]
[Required(ErrorMessage = "The {0} field is required.")]
public string AttributeFeatureCode { get; set; }
...
}
Result: The true field is required
data-val-required="The {0} field is required"
So I researched on web and I see that there is an error on GetErrorMessage
I guesss something is wrong in here... And I have to write override on my project.
public class RequiredAttributeAdapter : AttributeAdapterBase<RequiredAttribute>
{
public RequiredAttributeAdapter(RequiredAttribute attribute, IStringLocalizer stringLocalizer): base(attribute, stringLocalizer)
{
}
public override void AddValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-required", GetErrorMessage(context));
}
public override string GetErrorMessage(ModelValidationContextBase validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException(nameof(validationContext));
}
var errorMessage = GetErrorMessage(validationContext.ModelMetadata);
return string.Format(errorMessage, validationContext.ModelMetadata.GetDisplayName());
}
}
When I use it similar like this
return GetErrorMessage(validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName());
result is The {0} field is required
If I change it with override, that's working
var errorMessage = GetErrorMessage(validationContext.ModelMetadata);
return string.Format(errorMessage, validationContext.ModelMetadata.GetDisplayName());
What do you think ? is there any error on GetErrorMessage ?
Why I can get {0} ? and
why cant I get display name for {0}?
thanks a lot