为什么我不能将资源用作 ErrorMessage 和 DataAnnotations?

发布于 2024-08-30 00:12:05 字数 308 浏览 6 评论 0原文

为什么我不能这样做?

[Required(ErrorMessage = "*")]
[RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessage = Resources.RegistrationModel.UsernameError)]
public string Username { get; set; }

错误消息告诉我什么?

属性参数必须是 常量表达式 表达式或数组创建 属性参数的表达式 类型。

Why can't I do like this?

[Required(ErrorMessage = "*")]
[RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessage = Resources.RegistrationModel.UsernameError)]
public string Username { get; set; }

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

蒗幽 2024-09-06 00:12:05

当您使用 ErrorMessage 属性时,只能为其分配常量字符串或字符串文字。

请使用 ErrorMessageResourceTypeErrorMessageResourceName 来指定您的资源。

[RegularExpression(
    "^[a-zA-Z0-9_]*$", 
    ErrorMessageResourceType=typeof(Resources.RegistrationModel),
    ErrorMessageResourceName= "UsernameError"
)]

请注意,资源必须是公共(可以在资源编辑器中设置)。

When you are using the ErrorMessage property only constant strings or string literal can be assigned to it.

Use the ErrorMessageResourceType and ErrorMessageResourceName instead to specity your resources.

[RegularExpression(
    "^[a-zA-Z0-9_]*$", 
    ErrorMessageResourceType=typeof(Resources.RegistrationModel),
    ErrorMessageResourceName= "UsernameError"
)]

Note that the resources must be public (can be set in the resource editor).

Setting resource access to public

鹤仙姿 2024-09-06 00:12:05

请参阅此链接:http://code.msdn.microsoft.com/Getting-Started-WCF-RIA-1469cbe2/sourcecode?fileId=19242&pathId=774666288(链接已损坏,但出于归属目的而保留)

public sealed partial class RegistrationData 
{ 
    [Key] 
    [Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ErrorResources))] 
    [Display(Order = 0, Name = "UserNameLabel", ResourceType = typeof(RegistrationDataResources))] 
    [RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessageResourceName = "ValidationErrorInvalidUserName", ErrorMessageResourceType = typeof(ErrorResources))] 
    [StringLength(255, MinimumLength = 4, ErrorMessageResourceName = "ValidationErrorBadUserNameLength", ErrorMessageResourceType = typeof(ErrorResources))] 
    public string UserName { get; set; } 

Please see this link: http://code.msdn.microsoft.com/Getting-Started-WCF-RIA-1469cbe2/sourcecode?fileId=19242&pathId=774666288 (link broken, but left for attribution purposes)

public sealed partial class RegistrationData 
{ 
    [Key] 
    [Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ErrorResources))] 
    [Display(Order = 0, Name = "UserNameLabel", ResourceType = typeof(RegistrationDataResources))] 
    [RegularExpression("^[a-zA-Z0-9_]*$", ErrorMessageResourceName = "ValidationErrorInvalidUserName", ErrorMessageResourceType = typeof(ErrorResources))] 
    [StringLength(255, MinimumLength = 4, ErrorMessageResourceName = "ValidationErrorBadUserNameLength", ErrorMessageResourceType = typeof(ErrorResources))] 
    public string UserName { get; set; } 
财迷小姐 2024-09-06 00:12:05

尝试 FluentModelMetaDataProvider

设法以强类型的方式使用错误消息资源。

看起来像这样:

using System.Web.Mvc.Extensibility;

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

错误消息告诉我什么?

<块引用>

属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式。

这已经是不言自明的了。 C# 不是像 Ruby 这样的动态语言,您可以编写在运行时继承随机基类的类。 :)

这是 Skeet 对此的说法。

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<StoreInput>
    {
        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.

笑脸一如从前 2024-09-06 00:12:05

这意味着您无法确定在运行时传递到属性的参数值,它必须在编译时,以便该值嵌入到程序集中。

错误消息值需要是常量表达式。

有关信息,属性参数只能是 bool、byte、char、short、int、long、float、double、string、System.Type 和 enum 类型。

It means that you cannot determine the value of the argument you are passing into the attribute at runtime, it must be at compile time so the value is embedded into the assembly.

The error message value needs to be a constant expression.

For information, attribute arguments can only be of types bool, byte, char, short, int, long, float, double, string, System.Type, and enums.

小鸟爱天空丶 2024-09-06 00:12:05

您应该查看此属性的 ErrorMessageResourceNameErrorMessageResourceType 属性。它们确实允许从资源中提取错误消息。

You should instead look at the ErrorMessageResourceName and ErrorMessageResourceType properties of this attribute. They do allow the error message to be pulled from a resource.

南渊 2024-09-06 00:12:05

我们现在可以使用 nameof 来表示强类型错误消息:

[RegularExpression("^[a-zA-Z0-9_]*$", 
  ErrorMessageResourceType=typeof(Resources.RegistrationModel),
  ErrorMessageResourceName=nameof(Resources.RegistrationModel.UsernameError)
)]

We can now use nameof for strongly typed error messages:

[RegularExpression("^[a-zA-Z0-9_]*$", 
  ErrorMessageResourceType=typeof(Resources.RegistrationModel),
  ErrorMessageResourceName=nameof(Resources.RegistrationModel.UsernameError)
)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文