如何合并资源字符串以获取验证属性错误消息? [英] How do I combine resource strings for validation attribute error messages?

查看:62
本文介绍了如何合并资源字符串以获取验证属性错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要在诸如以下这样的验证属性上显示错误消息:

If I were to have error messages on a validation attribute like:

  • 必须输入名字
  • 姓氏为必填项

,然后是一个验证属性,如下所示:

and then a validation attribute like this:

[Required(ErrorMessageResourceName = "Error_FirstNameRequired", ErrorMessageResourceType = typeof(Strings)]
public string FirstName {get;set;}

我不想为每个实例进行翻译.有没有一种方法可以在格式化程序中组合资源字符串,例如:

I don't want to have a translation done for every instance of this. Is there a way to combine resource strings in a formatter, for example:

[Required(ErrorMessage = string.Format("{0} {1}", Strings.Label_FirstName, Strings.Error_IsRequired))]
public string FirstName {get;set;}

当然这是行不通的,因为它需要一个编译时间常数.但是是否有实现这一目标的途径,以便我可以构建本地化的字符串并重用已经存在的字符串?我想到的只是创建自定义属性,以允许设置额外的属性并覆盖默认输出消息,但这将导致过多的重构和繁琐的imo.

Of course this doesn't work because it needs to be a compile time constant. But is there away to achieve this so that I can build localized strings and reuse those that already exist? I thought of just creating custom attributes that allow for extra properties to be set and override the default output message, but that would be way too much refactoring and kind of kludgy imo.

有什么想法吗?

推荐答案

您可以在资源中定义的字符串中使用格式. 当使用{0}时,如FieldRequired所示,将在可能的情况下插入显示名称. 否则,它将退回到属性名称,如MiddleName所示.

You can use formatting in the strings defined in your resources. When you use {0}, as shown in FieldRequired, the display name will be inserted when possible. Otherwise it will fall back to the property name as shown for MiddleName.

示例:

Strings.resx

Strings.nl.resx

public class MyClass
{

    [Display(ResourceType = typeof(Strings), Name = "FirstName")]
    [Required(ErrorMessageResourceName = "FieldRequired",
              ErrorMessageResourceType = typeof(Strings))]
    public string FirstName { get; set; }

    [Required(ErrorMessageResourceName = "FieldRequired",
              ErrorMessageResourceType = typeof(Strings))]
    public string MiddleName { get; set; }

    [Display(ResourceType = typeof(Strings), Name = "LastName")]
    [Required(ErrorMessageResourceName = "FieldRequired",
              ErrorMessageResourceType = typeof(Strings))]
    public string LastName { get; set; }

    // Validation errors for culture [en] would be:
    //             "First name is a required field."
    //             "MiddleName is a required field."
    //             "Last name is a required field."
    //
    // Validation errors for culture [nl] would be:
    //             "Voornaam is een benodigd veld."
    //             "MiddleName is een benodigd veld."
    //             "Achternaam is een benodigd veld."
}

这篇关于如何合并资源字符串以获取验证属性错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆