0

My Model:

public class FPTAssetSummary : IValidatableObject
    {
    [Required]
    [Display(Name = "New Version")]
    public int ForatFrom { get; set; }

    [Required]
    [Display(Name = "Old Version")]
    public int ForatTo { get; set; }

    public List<FPTFORATExcel> FPTForatVersionList { get; set; }

    public IEnumerable<ValidationResult> Validate(
        ValidationContext validationContext)
    {
        if (ForatFrom <= ForatTo)
        {
            yield return new ValidationResult(
                "Old version must be higher than the new version");
        }
    }
}

My Controller:

    [HttpPost]
    public ActionResult ForatExcelCompare(FPTAssetSummary foratcompare)
    {

        var ExcelIDFrom = foratcompare.ForatFrom;
        var ExcelIDTo = foratcompare.ForatTo;

        return RedirectToAction("Index", new
        {
            ForatFrom = ExcelIDFrom,
            ForatTo = ExcelIDTo
        });
    }

Currently I am posting two integers from a view (2 dropdownboxes), to the controller below and passing the two values into the index with the two parameters (ForatFrom and ForatTo). However my IValidationObject method isn't returning the ValidationResult message. I think I need to check the model state in the ForatExcelCompare method, however I need to be able to return to the previous controller with the error message if the model state is false. Any Ideas?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Marc Howard
  • 395
  • 2
  • 6
  • 25
  • How are you displaying the error message in the view? Are you using the ValidationSummary helper? – Darin Dimitrov Nov 13 '13 at 17:12
  • Yes sorry, forgot to mention that i have set the @Html.ValidationSummary(true) – Marc Howard Nov 13 '13 at 17:16
  • Check out [this answer on SO](http://stackoverflow.com/a/6431986/2779990). It provides the following: `if (!ModelState.IsValid) { if (!model.Validated) { var validationResults = model.Validate(new ValidationContext(model, null, null)); foreach (var error in validationResults) foreach (var memberName in error.MemberNames) ModelState.AddModelError(memberName, error.ErrorMessage); } return View(post); }` – Stinky Towel Nov 13 '13 at 17:24

0 Answers0