Remote Attribute Sample in MVC: Day 29

In this article we will see how to apply a remote attribute in MVC.

In this sample we will check the dynamic validation of user input. We get two numbers from the end-user and check whether or not the second number is even using remote attribute. Remote attribute enables a client-side validation call to the server where the actual validation is done.

  1. Create an MVC project from the "Empty" template.

  2. Right-click on "Models", select "Add" >> "Class…".

    add new class

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

    add another class

  4. In the Calculate class create the two properties no1 and no2.

    calculate class

  5. Now add a controller, right-click on "Controllers", select "Add" >> "Controller…".

    add controller

  6. Select "MVC 5 Controller - Empty" to add an empty controller.

    Click on the "Add" button.

    empty mvc5 controller

  7. Name the controller as in the following:

    calcController

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

    add view

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

    type view name

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

    action result

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

    calcCalculate cs

  12. Name the view "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.

    create view

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

    html code

  14. Add the following JavaScript files in the head section of the Create.cshtml file.

    head section code

  15. Create an action method to validate the integer number. If the number is even then return the jsonresult object with the value true else return a jsonresult object with a message.

    create an action method

  16. In the model add a "Remote" attribute above the No2. Pass the action name that we want to call remotely and the controller name. Here we need to pass the IsValid action method where we define a logic for No2 to check whether or not it is even and Calc as the controller name.

    remote attribute

  17. Run the project, insert an odd number in No2 and you will get the message "Only Even Number".

    calculate


Similar Articles