So, I have an entity in my Models directory:
public class Event { public int Id { get; set; } [Required, MaxLength(50), MinLength(3)] public string Name { get; set; } [Required, MaxLength(2000)] public string Description { get; set; } }
and I want to open it for viewing using viewModel:
public class BaseEventViewModel { public string Name { get; set; } [DataType(DataType.MultilineText)] public string Description { get; set; } } public class EventCreateViewModel : BaseEventViewModel { }
My reasoning is that I want all data validation to be performed on entities, and all presentation materials (e.g., rendering of a text area) should be performed in a presentation model. Then I can use, however, many representation models that I want to represent as my entity, while preserving data integrity.
So, I changed my controller to use the new view model:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(EventCreateViewModel viewModel) { if (ModelState.IsValid) { db.Events.Add(new Event { Name = viewModel.Name, Description = viewModel.Description }); db.SaveChanges(); return RedirectToAction("Index"); } return View(viewModel); }
However, none of the entity checks are performed, and I can submit a blank form that throws a DbEntityValidationException .
Presumably this is because ModelState.IsValid working on a view model, not an object that represents a view model. How can I catch these validation errors?