Results 1 to 2 of 2

Thread: MVC Create Error:EntityValidationErrors

  1. #1
    Fanatic Member
    Join Date
    Oct 06
    Posts
    650

    MVC Create Error:EntityValidationErrors

    I have this on my Module

    Module
    Code:
        public class Person
        {
            public int ID { get; set; }
            [Required]
            [StringLength(30)]
            public string First { get; set; }
            [Required]
            [StringLength(30)]
            public string Last { get; set; }
            public DateTime BirthDate { get; set; }
        }
    
        public class PersonContext : DbContext
        {
            public DbSet<Person> People { get; set; }
        }
    and this on Controller

    Controller
    Code:
            // GET: /Person/Create
    
            public ActionResult Create(Person person)
            {
                db.People.Add(person);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    Every type I click the Create link, I'm encountering this error:

    Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,846

    Re: MVC Create Error:EntityValidationErrors

    You have validation attributes on the properties of your entity but your code is assuming that those attributes will never be violated. You need to check ModelState.IsValid to see whether the data entered by the user passes validation and only save it if it does. If it doesn't you need to redisplay the Create view with the validation errors so that the user can correct them.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •