Reputation: 2253
I implemented localization with DisplayName
and Required
attributes, it works fine with DisplayName
when I switch from English to Arabic language but for Required attribute - It is not getting updated with Arabic error message.
Below is the way I implemented and my code below:
DisplaName - Works fine in both language switching..
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]
public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
private ResourceUtils.Key _resourceKey;
public LocalizedDisplayNameAttribute(ResourceUtils.Key resourceKey)
: base()
{
_resourceKey = resourceKey;
}
public override string DisplayName
{
get
{
return ResourceUtils.GetDisplayName(_resourceKey);
}
}
}
It works fine, but only once - while switching from one language to another, it keeps old message of previous language after switching.. ErrorMessage doesn't get updated..
public class RequiredLocalizedAttribute : RequiredAttribute
{
public RequiredLocalizedAttribute(ResourceUtils.Key resourceKey)
{
this.ErrorMessage = ResourceUtils.GetDisplayName(resourceKey);
}
}
Global.asax
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredLocalizedAttribute), typeof(RequiredAttributeAdapter));
Modal code.
[LocalizedDisplayName(ResourceUtils.Key.Number)]
[RequiredLocalized(ResourceUtils.Key.NumberMessage)]
public int Number { get; set; }
What should I do? It is not working while switching language for ErrorMessage - DisplayName gets updated successfully while language switch.
Thanks.
Upvotes: 0
Views: 199
Reputation: 14741
Your custom required
attribute initialized just one time, not per request. And you set your error message in constructor. Therefore your error message is not updated.
Consider write custom factory for it. Or simply update your message in FormatErrorMessage
method:
public class RequiredLocalizedAttribute : RequiredAttribute
{
ResourceUtils.ResourceKey _resourceKey;
public RequiredLocalizedAttribute(ResourceUtils.ResourceKey resourceKey)
{
this._resourceKey = resourceKey;
}
public override string FormatErrorMessage(string name)
{
this.ErrorMessage = ResourceUtils.GetDisplayName(resourceKey);
return base.FormatErrorMessage(name);
}
}
Upvotes: 1