0

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

SUAT SUPHI
  • 417
  • 1
  • 4
  • 14

1 Answers1

0

there is a problem on SqlStringLocalizer.cs and line 40

so I changed it

public LocalizedString this[string name, params object[] arguments]
        {
            get
            {
                var str = this[name];
                if (arguments.Length > 0)
                    str = this[string.Format(str, arguments.Select(x => x.ToString()).ToArray())];
                return str;
            }
        }

if string contain string format I mean this {} so it will work for string format. I think my logic will work

SUAT SUPHI
  • 417
  • 1
  • 4
  • 14