Hi I have an Asp.NET MVC application in which I use data annotations to add validation to some fields:
[Required]
[DisplayName("Course Name")]
string Name { get; set; }
However this doesn't seem to work as I expected. Basically If the page contains any other errors that I manually check for and throw a new RuleViolation(), then the required violation is shown in the Validation Summary. If the required violation is the only error then it is not shown.
My controller has this code in it:
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
ModelState.AddRuleViolations(courseViewModel.Course.GetRuleViolations());
return View(courseViewModel);
}
But given that the required violation is not throwing, I never go in here.
Do I need to do something that I dont know about to trap errors raised by DataAnnotation violation?
Thanks for any help
Edit:
Here is the controller action:
[HttpPost]
[ValidateInput(true)]
public ActionResult Edit(int id, CourseViewModel courseViewModel)
{
var oldCourse = _eCaddyRepository.GetCourse(id);
if (courseViewModel.Course == null)
{
return View("NotFound", string.Format("Course {0} Not Found", id));
}
try
{
courseViewModel.Update(oldCourse);
_eCaddyRepository.SubmitChanges();
return RedirectToAction("Index", "Course");
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
ModelState.AddRuleViolations(courseViewModel.Course.GetRuleViolations());
return View(courseViewModel);
}
}
Where Update is :
public class CourseViewModel : BaseViewModel
{
public Course Course { get; set; }
public void Update(Course oldCourse)
{
oldCourse.Name = this.Course.Name != null ? this.Course.Name.Trim() : string.Empty;
oldCourse.Postcode = this.Course.Postcode != null ? this.Course.Postcode.Trim() : string.Empty;
for (var i = 0; i < 18; i++)
{
oldCourse.Holes[i].Par = this.Course.Holes[i].Par;
oldCourse.Holes[i].StrokeIndex = this.Course.Holes[i].StrokeIndex;
}
}
}
EDIT: Final code that works and validates as expected using dataannotations. Thanks to mare.
[HttpPost]
[ValidateInput(true)]
public ActionResult Edit(int id, CourseViewModel courseViewModel)
{
var oldCourse = _eCaddyRepository.GetCourse(id);
if (courseViewModel.Course == null)
{
return View("NotFound", string.Format("Course {0} Not Found", id));
}
if (ModelState.IsValid)
{
try
{
courseViewModel.Update(oldCourse);
_eCaddyRepository.SubmitChanges();
return RedirectToAction("Index", "Course");
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
}
// Return Model with errors
ModelState.AddRuleViolations(courseViewModel.Course.GetRuleViolations());
return View(courseViewModel);
}