验证ASP.NET MVC中的字符串数组

Yar*_*icx 4 asp.net validation asp.net-mvc

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

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

小智 5

您可以创建一个自定义验证属性: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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样使用:

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


小智 1

您应该使用自定义验证

[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);
    }
Run Code Online (Sandbox Code Playgroud)