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.
Create an MVC project from the "Empty" template.
Right-click on "Models", select "Add" >> "Class…".
Name the class "Calculating" and click on the "Add" button.
In the Calculate class create the two properties no1 and no2.
Now add a controller, right-click on "Controllers", select "Add" >> "Controller…".
Select "MVC 5 Controller - Empty" to add an empty controller.
Click on the "Add" button.
Name the controller as in the following:
Now add a view. Right-click on the "Index" action method and select "Add View...".
Name the view "Index". Select "Empty (without model)" from the templates. Click on the "Add" button.
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.
To add a view for the "Create" method, right-click on the "Create" action result method and select "Add View...".
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.
It will automatically create a view from the model.
Add the following JavaScript files in the head section of the Create.cshtml file.
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.
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.
Run the project, insert an odd number in No2 and you will get the message "Only Even Number".