Compare Validator Sample in MVC: Day 28

In this article we will see how to apply a compare validator in MVC.

  1. Create a MVC project from the "Empty" template.
  2. Right-click on "Models", select "Add" >> "Class...".



  3. Name the class "Calculate" and click on the "Add" button.



  4. In the calculate class, create two properties, no1 and no2.



  5. Now add a controller. Right-click on "Controllers" then select "Add" >> "Controller...".



  6. Select "MVC 5 Controller - Empty" to add an empty controller.
    Click on the "Add" button.



  7. Name the controller as in the following:



  8. Now add a view. Right-click on the "Index" action method and select "Add View...".



  9. Name the view as "Index".
    Select "Empty (without model)" from the templates.
    Click on the "Add" button.



  10. Now add two action result methods to the employee controller with the same name, one is for HttpGet and another one is for HttpPost. In the HttpPost "Create" method pass an Employee class object as parameter. When we press the create button it will call this HttpPost method.



  11. To add a view for the "Create" method, right-click on the "Create" action result method and select "Add View...".



  12. Name the view as "Create".
    As we will show, create a form to calculate, select "Create" from the template.
    From the model class drop down, select "Calculate" as the model.
    Click on the "Add" button.



  13. It will automatically create a view from the model.



  14. Add the "[Compare]" attribute to the field to be compared and pass the parameter that you want to compare with, in other words No1. Here we want to compare No2 with No1, so we set the compare attribute with No2 and pass the parameter as No1. The compare attribute requires the "System.ComponentModel.DataAnnotations" namespace.



  15. Now add two action result methods to the employee controller with the same name, one is for HttpGet and another one is for HttpPost. In the HttpPost "Create" method pass an Employee class object as the parameter. When we press the submit button it will call this HttpPost method.



  16. Run the project and call the "Create" action method of the Calc controller from the browser.



  17. Now insert two different numbers in the textboxes and press the "Create" button. The compare validation fails due to two different values and it throws the error message "No2 and No1 do not match".


<< Server Side Required Field Validator Sample in MVC: Day 27


Similar Articles