Why dataAnnotations dosen't valid the CourseList porperty of the Stuent?

31 Views Asked by At

When I used data System.ComponentModel.DataAnnotations, I had a problem. I defined a Student class that contains 2 attributes; one is the Name attribute and the other is the CourseList attribute; when I use the Validator.TryValidateObject method to verify the Sutent instance, there is no effect on CourseList. Who can help me

using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace C
{
    class Program
    {
        static void Main(string[] args)
        {
            var user = new Stuent();
            var context = new ValidationContext(user, null, null);
            var results = new List<ValidationResult>();
            Validator.TryValidateObject(user, context, results, true);
       }
}
public class Stuent
{
    [Required]
    public string Name { get; set; }

    public List<Course> CourseList { get; set; }

}
public class Course
{
    [Required]
    public string CourseName { get; set; }

}

}

Click on me by clicking on the mouse

1

There are 1 best solutions below

0
On

You have to create Custom Validation attribute to validate your CourseList Property.

I have made some changes in your above code and also create a custom validation attribute. Please check this link.

You can run and check this code that it will show validation message when you don't assign value to CourseName property.