【问题标题】:ASP.Net MVC : ValidationResult does not accept int.tostring() for member nameASP.Net MVC:ValidationResult 不接受成员名称的 int.tostring()
【发布时间】:2016-07-05 09:47:40
【问题描述】:

代码取自http://www.dotnetcurry.com/aspnet-mvc/1083/aspnet-mvc-self-validation-model-objects

public class Person : IValidatableObject
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        public string Address { get; set; }
        [Required]
        public DateTime BirthDate { get; set; }
        [Required]
        public int Income { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var pIncome = new[] { "Income" };
            if (Income < 0)
            {
                yield return new ValidationResult("Income cannot be negative", pIncome);
            }
            var pName = new[] { "Name" };
            if (Name.Length > 40)
            {
                yield return new ValidationResult("Name cannot be such huge in length", pName);
            }
            var pBDate = new[] { "BirthDate" };
            if (BirthDate > DateTime.Now)
            {
                yield return new ValidationResult("Sorry Future Date cannot be accepted.", pBDate);
            }

        }
    }

看到这一行

yield return new ValidationResult("Income cannot be negative", pIncome);

如果我这样写

yield return new ValidationResult("Income cannot be negative", Income.ToString());

然后得到错误但是当我们传递一个字符串变量时就没有问题了。所以如果我需要验证许多 int 类型的属性,那么我需要将这些属性名称放入

string array like  var pIncome = new[] { "Income" }; ?

如果数组中有很多元素名称,那么如何将其引用为ValidationResult ctor 的第二个参数?

请帮忙。谢谢

【问题讨论】:

    标签: asp.net-mvc-5


    【解决方案1】:

    如果我没记错的话,它应该是 collection (IEnumerable) ,所以它必须是 [] 类型。更改为 .tostring() 不会产生数组。

    public ValidationResult(string errorMessage, IEnumerable<string> memberNames); 
    

    此外,重载的 ctor 为模型中的一个或多个字段分配了验证错误,如果您想省略传递的成员名称,我猜该错误不会与任何字段相关联,而是与表单相关联。请在此处参考另一个不错的答案Assign ValidationResult to specific field?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-10
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多