MVC 中的非静态 ErrorMessage 数据注解

non-static ErrorMessage data annotation in MVC

我有一个可以用多种语言打开的站点,该站点的字符串是从产品所有者提供的 XML 文件中检索的。

该模型包含许多字段,但对于这个问题,我们只查看 FamilyName

public class RegisterViewModel
{
    public Translation Translation { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "LastNameEnter")]
    [Display(Name = "Last Name")]
    public string FamilyName { get; set; }
}

我以前使用上述格式为我的模型上的字段获取验证和必需的错误消息。现在虽然我们有一个帮助程序读取 XML 文件并创建一个包含 "Item" 列表的翻译对象,但每个项目都是一个具有其他一些属性的字符串。

我曾尝试将模型中的字段更改为以下格式,但它不起作用,因为出现以下错误:

An object reference is required for the non static field.

[Required(ErrorMessage = Translation.Item.Find(x => x.Id == "FamilyName " && x.Type == "Required").Text)]
public string FamilyName { get; set; }

如何使用非静态 Translation 属性.

设置错误消息

翻译 属性 在控制器的构造函数中设置。

编辑:

问题在于我的 Translation 对象实例化依赖于请求中的查询字符串。

string Language = !String.IsNullOrEmpty(Request.QueryString["l"])? Request.QueryString["l"]: "en-en";
model.Translation = RegistrationScriptHelper.Translation.GetRegistrationScript(Request).Find(x => x.Language == Language);

编辑 2: Global.asax.cs:

        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomRequiredAttribute),
        typeof(RequiredAttributeAdapter));

输出:

您需要编写自己的属性来实现此目的。这是一个例子:

public class MyReqAttribute : RequiredAttribute
{
    private string _errorID;
    public MyReqAttribute(string errorID)
    {
        _errorID=errorID;           
    }
    public override string FormatErrorMessage(string name)
    {
        string language = !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["l"])? HttpContext.Current.Request.QueryString["l"]: "en-en";
        var translation = RegistrationScriptHelper.Translation.GetRegistrationScript(HttpContext.Current.Request).Find(x => x.Language == language);

        this.ErrorMessage = translation.Item.Find(x => x.Id == errorID 
            && x.Type == "Required").Text;

        return base.FormatErrorMessage(name);
    }

}

并在 Global.asax.cs 文件中添加以下行:

protected void Application_Start()
{
    // other codes here

    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyReqAttribute), 
        typeof(RequiredAttributeAdapter));
}

然后你可以在你的模型中使用你自己的属性:

[MyReqAttribute("FamilyName")]
public string FamilyName { get; set; }