Remote Attribute Sample in MVC

Remote Attribute Sample in MVC

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…".

2.jpg

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

3.jpg In the Calculate class create the two properties no1 and no2.

4.jpg

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

5.jpg

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

Click on the "Add" button.

6.jpg

Name the controller as in the following:

7.jpg

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

8.jpg

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

9.jpg

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.

10.jpg

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

11.jpg

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.

12.jpg

It will automatically create a view from the model.

13.jpg

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

14.jpg

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.

15.jpg 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.

16.jpg

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

17.jpg