-
Notifications
You must be signed in to change notification settings - Fork 0
29 Validate the View Model Data in the Controller
M. Fares edited this page Apr 8, 2018
·
4 revisions
To validate or check the data that is in a view model, you may add your logic/code to the action in the controller. In this procedure, we will check the creation data of a department. This creation date should not be older than the current date by two day maximum (Just an example). You may compare two date such as start and end dates, difference between dates, you get the message.
You may also display messages to the user about the issue.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(DepartmentViewModel model)
{
if (ModelState.IsValid)
{
// Example on how to check the data in the view model
if (model.CreationDate < DateTime.Today.AddDays(-2))
{
// The message will be displayed in @Html.ValidationMessageFor(m => m.CreationDate)
ModelState.AddModelError("CreationDate", "The creation date should not be older than two days");
// The message will be displayed in @Html.ValidationSummary()
ModelState.AddModelError(String.Empty, "Issue with the creation date");
// Return the model with the entered dato to be corrected
return View(model);
}
Department department = Mapper.Map<DepartmentViewModel, Department>(model);
db.Departments.Add(department);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}