Why can't I use resources as ErrorMessage with DataAnnotations?

前端 未结 6 1971
眼角桃花
眼角桃花 2020-12-05 05:15

Why can\'t I do like this?

[Required(ErrorMessage = \"*\")]
[RegularExpression(\"^[a-zA-Z0-9_]*$\", ErrorMessage = Resources.RegistrationModel.UsernameError)         


        
6条回答
  •  感情败类
    2020-12-05 06:09

    Try FluentModelMetaDataProvider.

    Managed to use resources for error messages in strongly typed fashion.

    Looks like this:

    using System.Web.Mvc.Extensibility;
    
    namespace UI.Model
    {
        public class StoreInputMetadata : ModelMetadataConfigurationBase
        {
            public StoreInputMetadata()
            {
                Configure(m => m.Id)
                    .Hide();
                Configure(model => model.Name)
                    .Required(Resources.Whatever.StoreIsRequired)
                    .MaximumLength(64, Resources.Whatever.StoreNameLengthSomething);
            }
        }
    }
    

    What is the error message telling me?

    An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

    It's already self explanatory. C# isn't dynamic language like Ruby where You can write classes that inherits random base class at runtime. :)

    Here's what Skeet says about this.

提交回复
热议问题