开发者

Can I store Data Annotation Error Messages in an external file?

I am using data annotatio开发者_开发问答ns to validation my class properties. A requirement has emerged to store the validation error messages in an external file from which they would be loaded into memory at runtime.

I thought I'd be able to load a colleciton of error messages from an XML file and then set ErrorMessage:=[StringVariableHere] ... but apparently that doesn't work as you need to use a constant value.

If I store the errormessages in a Resource.resx file then those error messages are compiled into the project and can't be loaded at runtime - or am I wrong?

Can someone please advise me on a solution?


You can derive the Data Annotation attributes and provide your own source for the messages.

public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
    private string _displayName;

    public RequiredAttribute()
    {
        ErrorMessageResourceName = "Validation_Required";
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        _displayName = validationContext.DisplayName;
        return base.IsValid(value, validationContext);
    }

    public override string FormatErrorMessage(string name)
    {
        //LOOK HERE! ;)
        var msg = GetTheTextHereFromYourSource();

        return string.Format(msg, _displayName);
    }
}

I describe the technique in my blog (my goal was to get localized error messages, but the concept is the same): http://blog.gauffin.org/2010/11/simplified-localization-for-dataannotations/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜