简体   繁体   中英

How to display fluentvalidation error message on view

I've a fluent validator as below

[Validator(typeof(testvalidator))]
public class test
{
   .....
}

 public class testvalidator: AbstractValidator<test>
 {
     public testvalidator()
     {
        Custom(testvalidationmethod);
     }
     public ValidationFailure testvalidationmethod(test t)
     {
        return ValidationFailure("","error occurred in test validation method ");

     }

 } 

Usage

  testvalidator tv = new testvalidator();
  var result =tv.(test); 

I can see the error message in the result.Errors . But I want to display the error message on the view. I tried Html.ValidationSummary() with true and false . But didn't work. What need to be done to display on the view? I was reading tutorial . But it shows how to display on the console , which is hardly required in the real application. How do I make it work?

There is a method named AddToModelState , which needs to be called to add errors to ModelState . After that errors started showing up in the view.

Usage

public ActionResult DoSomething() {
  var customer = new Customer();
  var validator = new CustomerValidator();
  var results = validator.Validate(customer);

 results.AddToModelState(ModelState, null);
 return View();
}

Source of above fluentvalidation on github . Look at Manual Validations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM