【问题标题】:Validate String Array In ASP.NET MVC在 ASP.NET MVC 中验证字符串数组
【发布时间】:2015-11-03 09:16:53
【问题描述】:

我使用 ASP.NET MVC。如何在我的视图模型中验证字符串数组。因为“必需”属性不适用于字符串数组。

[DisplayName("Content Name")]
[Required(ErrorMessage = "Content name is required")]
public string[] ContentName { get; set; }

【问题讨论】:

  • 你想如何验证数组?它必须至少是一个元素?或者每个元素都不应该为 null 或为空?
  • 在模型上实现 IValidatableObject 并在其中执行自定义验证。或者在您的控制器中执行此操作并使用 ModelState.AddModelError() 记录错误

标签: asp.net asp.net-mvc validation


【解决方案1】:

您可以创建自定义验证属性:http://www.codeproject.com/Articles/260177/Custom-Validation-Attribute-in-ASP-NET-MVC

public class StringArrayRequiredAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid (object value, ValidationContext validationContext)
    {
        string[] array = value as string[];

        if(array == null || array.Any(item => string.IsNullOrEmpty(item)))
        {
            return new ValidationResult(this.ErrorMessage);
        }
        else
        {
            return ValidationResult.Success;
        }
    }
}

那么你可以这样使用:

[DisplayName("Content Name")]
[StringArrayRequired(ErrorMessage = "Content name is required")]
public string[] ContentName { get; set; }

【讨论】:

    【解决方案2】:

    您应该使用自定义验证

    [HttpPost]
        public ActionResult Index(TestModel model)
        {
            for (int i = 0; i < model.ContentName.Length; i++)
            {
                if (model.ContentName[i] == "")
                {
                    ModelState.AddModelError("", "Fill string!");
                    return View(model);
                }
            }
            return View(model);
        }
    

    【讨论】:

    • 在执行 for 循环之前需要检查 null
    • 我们的目标不是检查空值。需要检查空字符串。
    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 2013-08-19
    相关资源
    最近更新 更多