Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 数据批注验证属性中的字符串格式_C#_Asp.net Mvc_Model Binding - Fatal编程技术网

C# 数据批注验证属性中的字符串格式

C# 数据批注验证属性中的字符串格式,c#,asp.net-mvc,model-binding,C#,Asp.net Mvc,Model Binding,是否有任何方法可以使用格式化字符串而不是直接常量来设置数据注释消息 我需要像下面的代码一样设置必需的字段ErrorMessage,但它给了我一个错误 [Required(ErrorMessage = string.Format(SystemMessages.Required, "First Name"))] public string FirstName { get; set; } SystemMessages是一个常量文件,它有以下代码: public const string Requir

是否有任何方法可以使用格式化字符串而不是直接常量来设置数据注释消息

我需要像下面的代码一样设置必需的字段ErrorMessage,但它给了我一个错误

[Required(ErrorMessage = string.Format(SystemMessages.Required, "First Name"))]
public string FirstName { get; set; }
SystemMessages
是一个常量文件,它有以下代码:

public const string Required = "{0} is required.";

有没有办法设置这样的属性?

字符串。Format
结果不是编译时常量,编译器无法对其进行计算。属性值仅限于

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

更正式地说,您可以在中找到限制的描述。设置字符串格式不符合以下条件:

  • 简单类型(bool、byte、char、short、int、long、float和double)
  • 系统类型
  • 列举
  • 对象(object类型的属性参数的参数必须是上述类型之一的常量值。)
  • 上述任何一种类型的一维数组
充其量,您可以尝试类似的方法:

[Required(ErrorMessage = "First Name" + Required)]
public string FirstName { get; set; }


public const string Required = " is required.";
如果要输出显示名称而不是属性名称,请使用:

[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }

请实现使用
validatableobject
方法的
IValidatableObject
。它看起来像:

  public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
  {
       var memberNames = new List<string>();
       if (string.IsNullOrEmpty(this.FirstName )
        {
            memberNames.Add("FirstName");
            yield return new ValidationResult(string.Format(Resources.Required, "First Name"), memberNames);
        }
  }
公共IEnumerable验证(ValidationContext ValidationContext) { var memberNames=新列表(); if(string.IsNullOrEmpty(this.FirstName) { 成员姓名。添加(“名字”); 返回新的ValidationResult(string.Format(Resources.Required,“First Name”)、MemberName; } }
如果不清楚,请阅读
IValidatableObject
。祝你好运!

这是一个很好的解决方案,但我认为没有办法使用
IValidatableObject
进行远程验证,我很高兴这很有帮助。你说的“远程”验证是什么意思?你可以通过ajax请求将
remote
数据注释放入验证字段。但是在这种情况下,这似乎是不可能做到的