Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - MVC validator for integer array in model

I have used validator required field in my model as follow and its working

  [Required(ErrorMessage = "Description is required.")]
        public string Description { get; set; }

Now i have another property of integer array type

 public string[] Roles { get; set; }

I am not able to get how can i put required field validator on integer array ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Write a custom validation attribute.

I've not tested but try code like this :

public class RequiredArray : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count > 0;
        }
        return false;
    }
}

[RequiredArray (ErrorMessage = "Roles is required.")]
public string[] Roles{ get; set; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...